原创 LeetCode第42題之Trapping Rain Water

下面C++代碼只需一遍遍歷,具體分析見代碼註釋: #include <iostream> #include <vector> using namespace std; class Solution { public: i

原创 LeetCode第45之 Jump Game II

看了好幾種算法實現,感覺這裏說的最清楚,也比較簡單,本算法思想也是來源於此。 解法 看完這道題目,可能大部分的讀者都能夠想出這樣一個相對簡單的解法:將每個位置都看作一個點,並從第i個點向它之後的nums[i]個點都連一條長度爲1

原创 LeetCode第39題之Combination Sum(兩種方法)

思路:兩種方法都是利用遞歸回溯,第二方法在第一種方法的基礎上對原始數據先進行排序,這樣可以剪枝,加快計算速度。第一種方法在LeetCode上測試運行的時間是24ms,第二種方法運行時間爲16ms。 方法一: #include <

原创 LeetCode第18題之4Sum

Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all u

原创 LeetCode第29題之Divide Two Integers

C++代碼: #include <iostream> #include <limits> using namespace std; class Solution { public: int divide(int divi

原创 LeetCode第20題之Valid Parentheses

方法一:用棧實現 C++代碼: #include <stack> #include <iostream> using namespace std; //Given a string containing just the cha

原创 LeetCode第26題之Remove Duplicates from Sorted Array

在LeetCode上面運行了下,兩種方法用的時間差不多,猜測是因爲vector的迭代器就是普通指針,而數組首地址也可以看作指針,故兩種方法效率差不多。 C++代碼: 方法一: #include <vector> #includ

原创 LeetCode第19題之 Remove Nth Node From End of List

Given a linked list, remove the nth node from the end of list and return its head. For example, Given linked list:

原创 LeetCode第21題之Generate Parentheses(兩種解法)

C++代碼: 解法一(在LeetCode上運行效率高於解法二): #include <vector> #include <iostream> #include <string> using namespace std; cla

原创 LeetCode第34題之Search for a Range

C++代碼: #include <iostream> #include <vector> using namespace std; class Solution { public: vector<int> searchR

原创 LeetCode第40題之Combination Sum II

這一題主要是在上一題的基礎上解決重複解的問題。 C++代碼: #include <iostream> #include <algorithm> #include <vector> using namespace std; cl

原创 LeetCode第33題之 Search in Rotated Sorted Array

C++代碼: #include <iostream> #include <vector> using namespace std; class Solution { public: int search(vector<i

原创 LeetCode第37之Sudoku Solver

主要思路:回溯法,每個‘.’的位置遍歷“1-9”,如果滿足則繼續下一個位置,如果遍歷完“1-9”仍不滿足則將該位置改爲‘.’,然後回溯到上一個位置。 缺點就是運行時間有點長。 C++代碼: #include <iostream

原创 LeetCode第23題之Merge k Sorted Lists

樓主是參考:http://www.cnblogs.com/skysand/p/4300711.html,感覺這篇博客寫得挺好的。 C++代碼: #include <vector> #include <iostream> #incl

原创 LeetCode第25題之Reverse Nodes in k-Group

基本思想是對每k個節點採用頭插法,時間複雜度爲O(n)。 C++代碼: #include <vector> #include <iostream> using namespace std; /** * Definition