├── .gitignore ├── unique-binary-search-trees.cpp ├── palindrome-number.cpp ├── reverse-integer.cpp ├── best-time-to-buy-and-sell-stock-ii.cpp ├── length-of-last-word.cpp ├── plus-one.cpp ├── sqrtx.cpp ├── jump-game-ii.cpp ├── climbing-stairs.cpp ├── remove-duplicates-from-sorted-array.cpp ├── container-with-most-water.cpp ├── remove-element.cpp ├── single-number.cpp ├── convert-sorted-array-to-binary-search-tree.cpp ├── validate-binary-search-tree.cpp ├── first-missing-positive.cpp ├── best-time-to-buy-and-sell-stock.cpp ├── gas-station.cpp ├── divide-two-integers.cpp ├── pascals-triangle-ii.cpp ├── regular-expression-matching.cpp ├── unique-paths.cpp ├── triangle.cpp ├── gray-code.cpp ├── single-number-ii.cpp ├── powx-n.cpp ├── next-permutation.cpp ├── jump-game.cpp ├── maximum-depth-of-binary-tree.cpp ├── rotate-image.cpp ├── combinations.cpp ├── balanced-binary-tree.cpp ├── convert-sorted-list-to-binary-search-tree.cpp ├── implement-strstr.cpp ├── remove-duplicates-from-sorted-array-ii.cpp ├── merge-sorted-array.cpp ├── merge-two-sorted-lists.cpp ├── permutation-sequence.cpp ├── minimum-depth-of-binary-tree.cpp ├── maximum-product-subarray.cpp ├── largest-rectangle-in-histogram.cpp ├── rotate-list.cpp ├── swap-nodes-in-pairs.cpp ├── word-break.cpp ├── anagrams.cpp ├── longest-valid-parentheses.cpp ├── pascals-triangle.cpp ├── trapping-rain-water.cpp ├── linked-list-cycle.cpp ├── zigzag-conversion.cpp ├── add-binary.cpp ├── partition-list.cpp ├── sort-colors.cpp ├── search-insert-position.cpp ├── binary-tree-zigzag-level-order-traversal.cpp ├── same-tree.cpp ├── symmetric-tree.cpp ├── count-and-say.cpp ├── distinct-subsequences.cpp ├── longest-substring-without-repeating-characters.cpp ├── two-sum.cpp ├── unique-binary-search-trees-ii.cpp ├── string-to-integer-atoi.cpp ├── candy.cpp ├── minimum-path-sum.cpp ├── path-sum.cpp ├── roman-to-integer.cpp ├── remove-nth-node-from-end-of-list.cpp ├── spiral-matrix-ii.cpp ├── generate-parentheses.cpp ├── binary-tree-maximum-path-sum.cpp ├── n-queens-ii.cpp ├── remove-duplicates-from-sorted-list.cpp ├── search-in-rotated-sorted-array.cpp ├── decode-ways.cpp ├── longest-common-prefix.cpp ├── combination-sum.cpp ├── edit-distance.cpp ├── palindrome-partitioning-ii.cpp ├── permutations.cpp ├── linked-list-cycle-ii.cpp ├── merge-intervals.cpp ├── reverse-linked-list-ii.cpp ├── construct-binary-tree-from-preorder-and-inorder-traversal.cpp ├── insertion-sort-list.cpp ├── clone-graph.cpp ├── scramble-string.cpp ├── construct-binary-tree-from-inorder-and-postorder-traversal.cpp ├── search-in-rotated-sorted-array-ii.cpp ├── subsets.cpp ├── merge-k-sorted-lists.cpp ├── find-minimum-in-rotated-sorted-array.cpp ├── combination-sum-ii.cpp ├── intersection-of-two-linked-lists.cpp ├── binary-tree-inorder-traversal.cpp ├── maximum-subarray.cpp ├── multiply-strings.cpp ├── reverse-words-in-a-string.cpp ├── binary-tree-level-order-traversal.cpp ├── binary-tree-preorder-traversal.cpp ├── insert-interval.cpp ├── n-queens.cpp ├── subsets-ii.cpp ├── permutations-ii.cpp ├── search-for-a-range.cpp ├── binary-tree-level-order-traversal-ii.cpp ├── unique-paths-ii.cpp ├── flatten-binary-tree-to-linked-list.cpp ├── sum-root-to-leaf-numbers.cpp ├── median-of-two-sorted-arrays.cpp ├── valid-palindrome.cpp ├── simplify-path.cpp ├── remove-duplicates-from-sorted-list-ii.cpp ├── reverse-nodes-in-k-group.cpp ├── 3sum-closest.cpp ├── best-time-to-buy-and-sell-stock-iii.cpp ├── spiral-matrix.cpp ├── search-a-2d-matrix.cpp ├── substring-with-concatenation-of-all-words.cpp ├── add-two-numbers.cpp ├── palindrome-partitioning.cpp ├── integer-to-roman.cpp ├── lru-cache.cpp ├── 3sum.cpp ├── binary-tree-postorder-traversal.cpp ├── minimum-window-substring.cpp ├── letter-combinations-of-a-phone-number.cpp ├── maximal-rectangle.cpp ├── reorder-list.cpp ├── wildcard-matching.cpp ├── copy-list-with-random-pointer.cpp ├── find-minimum-in-rotated-sorted-array-ii.cpp ├── sudoku-solver.cpp ├── valid-number.cpp ├── populating-next-right-pointers-in-each-node.cpp ├── interleaving-string.cpp ├── restore-ip-addresses.cpp ├── set-matrix-zeroes.cpp ├── valid-parentheses.cpp ├── valid-sudoku.cpp ├── longest-palindromic-substring.cpp ├── text-justification.cpp ├── path-sum-ii.cpp ├── word-search.cpp ├── longest-consecutive-sequence.cpp ├── 4sum.cpp ├── sort-list.cpp ├── populating-next-right-pointers-in-each-node-ii.cpp ├── evaluate-reverse-polish-notation.cpp ├── recover-binary-search-tree.cpp ├── max-point-on-a-line.cpp ├── word-ladder.cpp ├── word-break-ii.cpp ├── leetcode.h ├── surrounded-regions.cpp └── word-ladder-ii.cpp /.gitignore: -------------------------------------------------------------------------------- 1 | a.out -------------------------------------------------------------------------------- /unique-binary-search-trees.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int numTrees(int n) { 6 | vector dp(n + 1, 0); 7 | dp[0] = 1; 8 | dp[1] = 1; 9 | 10 | for(int i = 2; i <= n; i++) { 11 | for(int j = 0; j < i; j++) { 12 | dp[i] += dp[j] * dp[i - j - 1]; 13 | } 14 | } 15 | 16 | return dp[n]; 17 | } 18 | }; 19 | 20 | int main() { 21 | return 0; 22 | } -------------------------------------------------------------------------------- /palindrome-number.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | bool isPalindrome(int x) { 6 | if(x < 0) { 7 | return false; 8 | } 9 | int o = x; 10 | int n = 0; 11 | while(o != 0) { 12 | int d = o % 10; 13 | n = 10 * n + d; 14 | o = o / 10; 15 | } 16 | 17 | return x == n; 18 | } 19 | }; 20 | 21 | int main() { 22 | Solution sln; 23 | cout << sln.isPalindrome(121) << endl; 24 | return 0; 25 | } -------------------------------------------------------------------------------- /reverse-integer.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int reverse(int x) { 6 | int neg = 1; 7 | if(x < 0) { 8 | neg = -1; 9 | x = -x; 10 | } 11 | 12 | int res = 0; 13 | while(x) { 14 | res = res * 10 + x % 10; 15 | x /= 10; 16 | } 17 | 18 | return res * neg; 19 | } 20 | }; 21 | 22 | int main() { 23 | Solution sln; 24 | 25 | cout << sln.reverse(123) << endl; 26 | cout << sln.reverse(-123) << endl; 27 | } -------------------------------------------------------------------------------- /best-time-to-buy-and-sell-stock-ii.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int maxProfit(vector &prices) { 6 | int len = (int)prices.size(); 7 | if(len <= 1) { 8 | return 0; 9 | } 10 | 11 | int sum = 0; 12 | for(int i = 1; i < len; i++) { 13 | if(prices[i] - prices[i - 1] > 0) { 14 | sum += prices[i] - prices[i - 1]; 15 | } 16 | } 17 | 18 | return sum; 19 | } 20 | }; 21 | 22 | int main() { 23 | return 0; 24 | } -------------------------------------------------------------------------------- /length-of-last-word.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int lengthOfLastWord(const char *s) { 6 | int len = strlen(s); 7 | int count = 0; 8 | for(int i = len - 1; i >= 0; i--) { 9 | if(s[i] == ' ') { 10 | if(count == 0) { 11 | continue; 12 | } else { 13 | return count; 14 | } 15 | } 16 | count++; 17 | } 18 | return count; 19 | } 20 | }; 21 | 22 | int main() { 23 | return 0; 24 | } -------------------------------------------------------------------------------- /plus-one.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | vector plusOne(vector &digits) { 6 | vector res(digits.size(), 0); 7 | int sum = 0; 8 | int one = 1; 9 | for(int i = digits.size() - 1; i >= 0; i--) { 10 | sum = one + digits[i]; 11 | one = sum / 10; 12 | res[i] = sum % 10; 13 | } 14 | 15 | if(one > 0) { 16 | res.insert(res.begin(), one); 17 | } 18 | return res; 19 | } 20 | }; 21 | 22 | int main() { 23 | return 0; 24 | } -------------------------------------------------------------------------------- /sqrtx.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int sqrt(int x) { 6 | long long i = 0; 7 | long long j = x / 2 + 1; 8 | while(i <= j) { 9 | long long mid = (i + j) / 2; 10 | long long sq = mid * mid; 11 | if(sq == x) { 12 | return mid; 13 | } else if(sq < x) { 14 | i = mid + 1; 15 | } else { 16 | j = mid - 1; 17 | } 18 | } 19 | return j; 20 | } 21 | }; 22 | 23 | int main() { 24 | return 0; 25 | } -------------------------------------------------------------------------------- /jump-game-ii.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int jump(int A[], int n) { 6 | int ret = 0; 7 | int last = 0; 8 | int curr = 0; 9 | for(int i = 0; i < n; i++) { 10 | if(i > last) { 11 | last = curr; 12 | ++ret; 13 | } 14 | curr = max(curr, i + A[i]); 15 | } 16 | return ret; 17 | } 18 | }; 19 | 20 | int main() { 21 | Solution sln; 22 | 23 | int a[] = {2, 3, 1, 1, 4}; 24 | 25 | cout << sln.jump(a, 5) << endl; 26 | 27 | return 0; 28 | } -------------------------------------------------------------------------------- /climbing-stairs.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int climbStairs(int n) { 6 | int f1 = 2; 7 | int f2 = 1; 8 | if(n == 1) { 9 | return f2; 10 | } else if(n == 2) { 11 | return f1; 12 | } 13 | 14 | int fn; 15 | for(int i = 3; i <= n; i++) { 16 | fn = f1 + f2; 17 | f2 = f1; 18 | f1 = fn; 19 | } 20 | return fn; 21 | } 22 | }; 23 | 24 | int main() { 25 | Solution sln; 26 | cout << sln.climbStairs(4) << endl; 27 | return 0; 28 | } -------------------------------------------------------------------------------- /remove-duplicates-from-sorted-array.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int removeDuplicates(int A[], int n) { 6 | if(n == 0) { 7 | return 0; 8 | } 9 | 10 | int index = 0; 11 | for(int i = 1; i < n; i++) { 12 | if(A[index] != A[i]) { 13 | A[++index] = A[i]; 14 | } 15 | } 16 | return index + 1; 17 | } 18 | }; 19 | 20 | int main() { 21 | Solution sln; 22 | 23 | int a[] = {1, 1, 2}; 24 | 25 | cout << sln.removeDuplicates(a, 3) << endl; 26 | 27 | return 0; 28 | } -------------------------------------------------------------------------------- /container-with-most-water.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int maxArea(vector &height) { 6 | int s = 0; 7 | int e = height.size() - 1; 8 | int a = numeric_limits::min(); 9 | 10 | while(s < e) { 11 | int c = min(height[s], height[e]) * (e - s); 12 | a = max(a, c); 13 | 14 | if(height[s] <= height[e]) { 15 | s++; 16 | } else { 17 | e--; 18 | } 19 | } 20 | 21 | return a; 22 | } 23 | }; 24 | 25 | int main() { 26 | return 0; 27 | } -------------------------------------------------------------------------------- /remove-element.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int removeElement(int A[], int n, int elem) { 6 | int i = 0; 7 | int j = 0; 8 | for(i = 0; i < n; i++) { 9 | if(A[i] == elem) { 10 | continue; 11 | } 12 | 13 | A[j] = A[i]; 14 | j++; 15 | } 16 | 17 | return j; 18 | } 19 | }; 20 | 21 | int main() { 22 | Solution sln; 23 | 24 | int a[] = {4, 4}; 25 | int n = sizeof(a) / sizeof(int); 26 | 27 | cout << sln.removeElement(a, n, 3) << endl; 28 | 29 | return 0; 30 | } -------------------------------------------------------------------------------- /single-number.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int singleNumber(int A[], int n) { 6 | int t = 0; 7 | 8 | for(int i = 0; i < n; i++) { 9 | t ^= A[i]; 10 | } 11 | 12 | return t; 13 | } 14 | }; 15 | 16 | int main() { 17 | int a[] = {1, 2, 1, 9, 2}; 18 | Solution sln; 19 | 20 | cout << sln.singleNumber(a, 5) << endl; 21 | 22 | int b[] = {1, 2, 1, 7, 2}; 23 | 24 | cout << sln.singleNumber(b, 5) << endl; 25 | 26 | int c[] = {1, 0, 1}; 27 | 28 | cout << sln.singleNumber(c, 3) << endl; 29 | 30 | 31 | return 0; 32 | } -------------------------------------------------------------------------------- /convert-sorted-array-to-binary-search-tree.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | TreeNode *sortedArrayToBST(vector &num) { 6 | return build(num, 0, num.size()); 7 | } 8 | 9 | TreeNode* build(vector& num, int start, int end) { 10 | if(start >= end) { 11 | return NULL; 12 | } 13 | 14 | int mid = (start + end) / 2; 15 | 16 | TreeNode* node = new TreeNode(num[mid]); 17 | node->left = build(num, start, mid); 18 | node->right = build(num, mid + 1, end); 19 | 20 | return node; 21 | } 22 | }; 23 | 24 | int main() { 25 | 26 | } -------------------------------------------------------------------------------- /validate-binary-search-tree.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | bool isValidBST(TreeNode *root) { 6 | return valid(root, numeric_limits::min(), numeric_limits::max()); 7 | } 8 | 9 | bool valid(TreeNode* node, int minVal, int maxVal) { 10 | if(!node) { 11 | return true; 12 | } 13 | 14 | if(node->val <= minVal || node->val >= maxVal) { 15 | return false; 16 | } 17 | 18 | return valid(node->left, minVal, node->val) && 19 | valid(node->right, node->val, maxVal); 20 | } 21 | }; 22 | 23 | int main() { 24 | return 0; 25 | } -------------------------------------------------------------------------------- /first-missing-positive.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int firstMissingPositive(int A[], int n) { 6 | if(n == 0) { 7 | return 1; 8 | } 9 | 10 | for(int i = 0; i < n; i++) { 11 | while(A[i] != i + 1 && A[i] >= 1 && A[i] <= n && A[i] != A[A[i] - 1]) { 12 | swap(A[i], A[A[i] - 1]); 13 | } 14 | } 15 | 16 | for(int i = 0; i < n; i++) { 17 | if(A[i] != i + 1) { 18 | return i + 1; 19 | } 20 | } 21 | 22 | return n + 1; 23 | } 24 | }; 25 | 26 | int main() { 27 | return 0; 28 | } -------------------------------------------------------------------------------- /best-time-to-buy-and-sell-stock.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int maxProfit(vector &prices) { 6 | if(prices.size() <= 1) { 7 | return 0; 8 | } 9 | 10 | int minP = prices[0]; 11 | 12 | int profit = prices[1] - prices[0]; 13 | 14 | for(int i = 2; i < prices.size(); i++) { 15 | minP = min(prices[i - 1], minP); 16 | profit = max(profit, prices[i] - minP); 17 | } 18 | 19 | if(profit < 0) { 20 | return 0; 21 | } 22 | 23 | return profit; 24 | } 25 | }; 26 | 27 | int main() { 28 | return 0; 29 | } -------------------------------------------------------------------------------- /gas-station.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int canCompleteCircuit(vector &gas, vector &cost) { 6 | int sum = 0; 7 | int total = 0; 8 | int k = 0; 9 | for(int i = 0; i < (int)gas.size(); i++) { 10 | sum += gas[i] - cost[i]; 11 | if(sum < 0) { 12 | k = i + 1; 13 | sum = 0; 14 | } 15 | total += gas[i] - cost[i]; 16 | } 17 | 18 | if(total < 0) { 19 | return -1; 20 | } else { 21 | return k; 22 | } 23 | } 24 | }; 25 | 26 | int main() { 27 | return 0; 28 | } -------------------------------------------------------------------------------- /divide-two-integers.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int divide(int dividend, int divisor) { 6 | long long a = abs((double)dividend); 7 | long long b = abs((double)divisor); 8 | int r = 0; 9 | while(a >= b) { 10 | long long t = b; 11 | for(int i = 1; a >= t; i <<= 1, t <<= 1) { 12 | a -= t; 13 | r += i; 14 | } 15 | } 16 | return ((dividend < 0) ^ (dividend < 0)) ? -r : r; 17 | } 18 | }; 19 | 20 | int main() { 21 | Solution sln; 22 | 23 | cout << sln.divide(-2147483648, 1) << endl; 24 | 25 | return 0; 26 | } -------------------------------------------------------------------------------- /pascals-triangle-ii.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | vector getRow(int rowIndex) { 6 | vector vals; 7 | 8 | vals.resize(rowIndex + 1, 1); 9 | 10 | for(int i = 0; i < rowIndex + 1; ++i) { 11 | for(int j = i - 1; j >= 1; --j) { 12 | vals[j] = vals[j] + vals[j - 1]; 13 | } 14 | 15 | } 16 | 17 | return vals; 18 | } 19 | }; 20 | 21 | int main() { 22 | Solution sln; 23 | 24 | auto a = sln.getRow(3); 25 | for(int i = 0; i < a.size(); i++) { 26 | cout << a[i] << "\t"; 27 | } 28 | 29 | cout << endl; 30 | return 0; 31 | } -------------------------------------------------------------------------------- /regular-expression-matching.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | bool isMatch(const char *s, const char *p) { 6 | if(!*p) { 7 | return !*s; 8 | } 9 | 10 | if(*(p + 1) == '*') { 11 | while(*s && (*s == *p || '.' == *p)) { 12 | if(isMatch(s, p + 2)) { 13 | return true; 14 | } 15 | s++; 16 | } 17 | 18 | return isMatch(s, p + 2); 19 | } else { 20 | return (*s == *p || (*s && '.' == *p)) && isMatch(s + 1, p + 1); 21 | } 22 | } 23 | }; 24 | 25 | int main() { 26 | return 0; 27 | } -------------------------------------------------------------------------------- /unique-paths.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int uniquePaths(int m, int n) { 6 | int dp[m][n]; 7 | for(int i = 0; i < m; i++) { 8 | dp[i][0] = 1; 9 | } 10 | 11 | for(int j = 0; j < n; j++) { 12 | dp[0][j] = 1; 13 | } 14 | 15 | for(int i = 1; i < m; i++) { 16 | for(int j = 1; j < n; j++) { 17 | dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; 18 | } 19 | } 20 | 21 | return dp[m - 1][n - 1]; 22 | } 23 | }; 24 | 25 | int main() { 26 | Solution sln; 27 | 28 | cout << sln.uniquePaths(3, 7) << endl; 29 | return 0; 30 | } -------------------------------------------------------------------------------- /triangle.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int minimumTotal(vector > &triangle) { 6 | if(triangle.empty()) { 7 | return 0; 8 | } 9 | int row = triangle.size(); 10 | vector dp; 11 | dp.resize(row); 12 | for(int i = 0; i < dp.size(); i++) { 13 | dp[i] = triangle[row-1][i]; 14 | } 15 | 16 | for(int i = row - 2; i >= 0; i--) { 17 | for(int j = 0; j <= i; j++) { 18 | dp[j] = triangle[i][j] + min(dp[j], dp[j + 1]); 19 | } 20 | } 21 | return dp[0]; 22 | } 23 | }; 24 | 25 | int main() { 26 | return 0; 27 | } -------------------------------------------------------------------------------- /gray-code.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | vector grayCode(int n) { 6 | vector v; 7 | 8 | v.push_back(0); 9 | 10 | for(int i = 0; i < n; i++) { 11 | int h = 1 << i; 12 | int len = v.size(); 13 | 14 | for(int j = len - 1; j >= 0; j--) { 15 | v.push_back(h + v[j]); 16 | } 17 | } 18 | 19 | return v; 20 | } 21 | }; 22 | 23 | int main() { 24 | Solution sln; 25 | 26 | auto a = sln.grayCode(2); 27 | 28 | for(int i = 0; i < a.size(); i++) { 29 | cout << a[i] << "\t"; 30 | } 31 | 32 | cout << endl; 33 | 34 | return 0; 35 | } -------------------------------------------------------------------------------- /single-number-ii.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int singleNumber(int A[], int n) { 6 | int r = 0; 7 | for(int i = 0; i < 32; i++) { 8 | int c = 0; 9 | int b = 1 << i; 10 | for(int j = 0; j < n; j++) { 11 | if(A[j] & b) { 12 | c++; 13 | } 14 | } 15 | 16 | if(c % 3) { 17 | r |= b; 18 | } 19 | } 20 | return r; 21 | } 22 | }; 23 | 24 | int main() { 25 | int a[] = {1, 1, 1, 0}; 26 | 27 | Solution sln; 28 | 29 | cout << sln.singleNumber(a, sizeof(a) / sizeof(int)) << endl; 30 | 31 | return 0; 32 | } -------------------------------------------------------------------------------- /powx-n.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | double power(double x, int n) { 6 | if(n == 0) { 7 | return 1; 8 | } else if(n == 1) { 9 | return x; 10 | } 11 | 12 | double v = pow(x, n / 2); 13 | if(n % 2 == 0) { 14 | return v * v; 15 | } else { 16 | return v * v * x; 17 | } 18 | } 19 | 20 | double pow(double x, int n) { 21 | if(n < 0) { 22 | return 1.0 / power(x, -n); 23 | } else { 24 | return power(x, n); 25 | } 26 | } 27 | }; 28 | 29 | int main() { 30 | Solution sln; 31 | cout << sln.pow(2, 2) << endl; 32 | return 0; 33 | } -------------------------------------------------------------------------------- /next-permutation.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | void nextPermutation(vector &num) { 6 | int len = num.size(); 7 | for(int i = len - 2; i >= 0; i--) { 8 | if(num[i + 1] > num[i]) { 9 | int j; 10 | for(j = len - 1; j > i; j--) { 11 | if(num[j] > num[i]) { 12 | break; 13 | } 14 | } 15 | swap(num[i], num[j]); 16 | reverse(num.begin() + i + 1, num.end()); 17 | return; 18 | } 19 | } 20 | reverse(num.begin(), num.end()); 21 | } 22 | }; 23 | 24 | int main() { 25 | return 0; 26 | } -------------------------------------------------------------------------------- /jump-game.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | bool canJump(int A[], int n) { 6 | if(n == 0) { 7 | return true; 8 | } 9 | 10 | int v = A[0]; 11 | 12 | for(int i = 1; i < n; i++) { 13 | v--; 14 | if(v < 0) { 15 | return false; 16 | } 17 | 18 | if(v < A[i]) { 19 | v = A[i]; 20 | } 21 | } 22 | return true; 23 | } 24 | }; 25 | 26 | int main() { 27 | Solution sln; 28 | 29 | int a[] = {2, 3, 1, 1, 4}; 30 | cout << sln.canJump(a, 5) << endl; 31 | 32 | int b[] = {3, 2, 1, 0, 4}; 33 | cout << sln.canJump(b, 5) << endl; 34 | 35 | 36 | return 0; 37 | } -------------------------------------------------------------------------------- /maximum-depth-of-binary-tree.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int num; 6 | int maxDepth(TreeNode *root) { 7 | if(!root) { 8 | return 0; 9 | } 10 | 11 | num = numeric_limits::min(); 12 | travel(root, 1); 13 | return num; 14 | } 15 | 16 | void travel(TreeNode* node, int level) { 17 | if(!node->left && !node->right) { 18 | num = max(num, level); 19 | return; 20 | } 21 | 22 | if(node->left) { 23 | travel(node->left, level + 1); 24 | } 25 | 26 | if(node->right) { 27 | travel(node->right, level + 1); 28 | } 29 | } 30 | }; 31 | 32 | int main() { 33 | return 0; 34 | } -------------------------------------------------------------------------------- /rotate-image.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | void rotate(vector > &matrix) { 6 | int n = matrix.size(); 7 | if(n == 0) { 8 | return ; 9 | } 10 | 11 | int a = n; 12 | for(int i = 0; i < n / 2; i++, a -= 2) { 13 | int m = a - 1; 14 | for(int j = 0; j < m; j++) { 15 | int t = matrix[i][i + j]; 16 | matrix[i][i +j] = matrix[i + m - j][i]; 17 | matrix[i + m - j][i] = matrix[i + m][i + m -j]; 18 | matrix[i + m][i + m - j] = matrix[i + j][i + m]; 19 | matrix[i + j][i + m] = t; 20 | } 21 | } 22 | } 23 | }; 24 | 25 | int main() { 26 | return 0; 27 | } -------------------------------------------------------------------------------- /combinations.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | vector > vv; 6 | 7 | vector > combine(int n, int k) { 8 | vector v; 9 | 10 | dfs(v, 1, n, k); 11 | 12 | return vv; 13 | } 14 | 15 | 16 | void dfs(vector& v, int start, int n, int k) { 17 | if(0 == k) { 18 | vv.push_back(v); 19 | return; 20 | } 21 | 22 | for(int i = start; i <= n; i++) { 23 | v.push_back(i); 24 | dfs(v, i + 1, n, k - 1); 25 | v.pop_back(); 26 | } 27 | 28 | } 29 | }; 30 | 31 | int main() { 32 | Solution sln; 33 | 34 | auto a = sln.combine(4, 2); 35 | 36 | printVector2(a); 37 | 38 | return 0; 39 | } -------------------------------------------------------------------------------- /balanced-binary-tree.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | bool isBalanced(TreeNode *root) { 6 | if(!root) { 7 | return true; 8 | } 9 | 10 | int d = 1; 11 | return depth(root, d); 12 | } 13 | 14 | bool depth(TreeNode* node, int& d) { 15 | if(!node) { 16 | d = 0; 17 | return true; 18 | } 19 | int left, right; 20 | if(depth(node->left, left) && depth(node->right, right)) { 21 | if(abs(left - right) > 1) { 22 | return false; 23 | } 24 | 25 | d = 1 + max(left, right); 26 | return true; 27 | } 28 | return false; 29 | } 30 | }; 31 | 32 | int main() { 33 | return 0; 34 | } -------------------------------------------------------------------------------- /convert-sorted-list-to-binary-search-tree.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | TreeNode *sortedListToBST(ListNode *head) { 6 | return build(head, NULL); 7 | } 8 | 9 | TreeNode* build(ListNode* start, ListNode* end) { 10 | if(start == end) { 11 | return NULL; 12 | } 13 | 14 | ListNode* fast = start; 15 | ListNode* slow = start; 16 | 17 | while(fast != end && fast->next != end) { 18 | slow = slow->next; 19 | fast = fast->next->next; 20 | } 21 | 22 | TreeNode* node = new TreeNode(slow->val); 23 | node->left = build(start, slow); 24 | node->right = build(slow->next, end); 25 | 26 | return node; 27 | } 28 | }; 29 | 30 | int main() { 31 | return 0; 32 | } -------------------------------------------------------------------------------- /implement-strstr.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | char *strStr(char *haystack, char *needle) { 6 | if(!haystack || !needle) { 7 | return NULL; 8 | } 9 | 10 | int hLen = strlen(haystack); 11 | int nLen = strlen(needle); 12 | if(hLen < nLen) { 13 | return NULL; 14 | } 15 | 16 | for(int i = 0; i < hLen - nLen + 1; i++) { 17 | int j = 0; 18 | for(j = 0; j < nLen; j++) { 19 | if(haystack[i + j] != needle[j]) { 20 | break; 21 | } 22 | } 23 | if(j == nLen) { 24 | return &haystack[i]; 25 | } 26 | } 27 | return NULL; 28 | } 29 | }; 30 | 31 | int main() { 32 | return 0; 33 | } -------------------------------------------------------------------------------- /remove-duplicates-from-sorted-array-ii.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int removeDuplicates(int A[], int n) { 6 | if(n == 0) { 7 | return 0; 8 | } 9 | 10 | int index = 0; 11 | int num = 0; 12 | for(int i = 1; i < n; i++) { 13 | if(A[index] == A[i]) { 14 | num++; 15 | if(num < 2) { 16 | A[++index] = A[i]; 17 | } 18 | } else { 19 | A[++index] = A[i]; 20 | num = 0; 21 | } 22 | } 23 | return index + 1; 24 | } 25 | }; 26 | 27 | int main() { 28 | Solution sln; 29 | 30 | int a[] = {1, 1, 1, 2, 2, 3}; 31 | 32 | cout << sln.removeDuplicates(a, 6) << endl; 33 | 34 | return 0; 35 | } -------------------------------------------------------------------------------- /merge-sorted-array.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | void merge(int A[], int m, int B[], int n) { 6 | int i = m + n - 1; 7 | int j = m - 1; 8 | int k = n - 1; 9 | 10 | while(i >= 0) { 11 | if(j >= 0 && k >= 0) { 12 | if(A[j] > B[k]) { 13 | A[i] = A[j]; 14 | j--; 15 | } else { 16 | A[i] = B[k]; 17 | k--; 18 | } 19 | } else if(j >= 0) { 20 | A[i] = A[j]; 21 | j--; 22 | } else if(k >= 0) { 23 | A[i] = B[k]; 24 | k--; 25 | } 26 | i--; 27 | } 28 | } 29 | }; 30 | 31 | int main() { 32 | return 0; 33 | } -------------------------------------------------------------------------------- /merge-two-sorted-lists.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { 6 | ListNode dummy(0); 7 | ListNode* p = &dummy; 8 | 9 | while(l1 && l2) { 10 | int val1 = l1->val; 11 | int val2 = l2->val; 12 | if(val1 < val2) { 13 | p->next = l1; 14 | p = l1; 15 | l1 = l1->next; 16 | } else { 17 | p->next = l2; 18 | p = l2; 19 | l2 = l2->next; 20 | } 21 | } 22 | 23 | if(l1) { 24 | p->next = l1; 25 | } else if(l2) { 26 | p->next = l2; 27 | } 28 | 29 | return dummy.next; 30 | } 31 | }; 32 | 33 | int main() { 34 | return 0; 35 | } -------------------------------------------------------------------------------- /permutation-sequence.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | string getPermutation(int n, int k) { 6 | vector num(n); 7 | int fab = 1; 8 | for(int i = 0; i < n; i++) { 9 | num[i] = i + 1; 10 | fab *= (i + 1); 11 | } 12 | 13 | k--; 14 | string s; 15 | for(int i = 0; i < n; i++) { 16 | fab = fab / (n - i); 17 | int p = k / fab; 18 | s.push_back(num[p] + '0'); 19 | for(int j = p; j < n - i; j++) { 20 | num[j] = num[j + 1]; 21 | } 22 | 23 | k = k % fab; 24 | } 25 | return s; 26 | } 27 | }; 28 | 29 | int main() { 30 | Solution sln; 31 | 32 | cout << sln.getPermutation(3, 4) << endl; 33 | 34 | 35 | return 0; 36 | } -------------------------------------------------------------------------------- /minimum-depth-of-binary-tree.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int n; 6 | int minDepth(TreeNode *root) { 7 | if(!root) { 8 | return 0; 9 | } 10 | 11 | n = numeric_limits::max(); 12 | int d = 1; 13 | 14 | depth(root, d); 15 | return n; 16 | } 17 | 18 | void depth(TreeNode* node, int& d) { 19 | if(!node->left && !node->right) { 20 | n = min(n, d); 21 | return; 22 | } 23 | 24 | if(node->left) { 25 | d++; 26 | depth(node->left, d); 27 | d--; 28 | } 29 | 30 | if(node->right) { 31 | d++; 32 | depth(node->right, d); 33 | d--; 34 | } 35 | } 36 | }; 37 | 38 | int main() { 39 | return 0; 40 | } -------------------------------------------------------------------------------- /maximum-product-subarray.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int maxProduct(int A[], int n) { 6 | if(n == 0){ 7 | return 0; 8 | } else if(n == 1) { 9 | return A[0]; 10 | } 11 | 12 | int p = A[0]; 13 | int maxP = A[0]; 14 | int minP = A[0]; 15 | for(int i = 1; i < n; i++) { 16 | int t = maxP; 17 | maxP = max(max(maxP * A[i], A[i]), minP * A[i]); 18 | minP = min(min(t * A[i], A[i]), minP * A[i]); 19 | p = max(maxP, p); 20 | } 21 | 22 | return p; 23 | } 24 | }; 25 | 26 | int main() { 27 | int a[] = {2, 3, -2, 4}; 28 | int n = sizeof(a) / sizeof(int); 29 | 30 | Solution sln; 31 | int m = sln.maxProduct(a, n); 32 | cout << m << endl; 33 | 34 | return 0; 35 | } -------------------------------------------------------------------------------- /largest-rectangle-in-histogram.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int largestRectangleArea(vector &height) { 6 | vector s; 7 | height.push_back(0); 8 | 9 | int sum = 0; 10 | int i = 0; 11 | while(i < height.size()) { 12 | if(s.empty() || height[i] > height[s.back()]) { 13 | s.push_back(i); 14 | i++; 15 | } else { 16 | int t = s.back(); 17 | s.pop_back(); 18 | sum = max(sum, height[t] * (s.empty() ? i : i - s.back() - 1)); 19 | } 20 | } 21 | 22 | return sum; 23 | } 24 | }; 25 | 26 | int main() { 27 | vector height({1, 1}); 28 | 29 | Solution sln; 30 | cout << sln.largestRectangleArea(height) << endl; 31 | 32 | return 0; 33 | } -------------------------------------------------------------------------------- /rotate-list.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | ListNode *rotateRight(ListNode *head, int k) { 6 | if(!head || k == 0) { 7 | return head; 8 | } 9 | 10 | int n = 1; 11 | ListNode* p = head; 12 | while(p->next) { 13 | p = p->next; 14 | n++; 15 | } 16 | 17 | k = n - k % n; 18 | p->next = head; 19 | 20 | for(int i = 0; i < k; i++) { 21 | p = p->next; 22 | } 23 | 24 | head = p->next; 25 | p->next = NULL; 26 | return head; 27 | } 28 | 29 | 30 | }; 31 | 32 | int main() { 33 | Solution sln; 34 | 35 | ListNode* n1 = createListNode(vector({1, 2, 3, 4, 5})); 36 | 37 | n1 = sln.rotateRight(n1, 2); 38 | 39 | printListNode(n1); 40 | 41 | return 0; 42 | } -------------------------------------------------------------------------------- /swap-nodes-in-pairs.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | ListNode *swapPairs(ListNode *head) { 6 | if(!head || !head->next) { 7 | return head; 8 | } 9 | 10 | ListNode dummy(0); 11 | ListNode* p = &dummy; 12 | dummy.next = head; 13 | 14 | while(p && p->next && p->next->next) { 15 | ListNode* n = p->next; 16 | ListNode* nn = p->next->next; 17 | p->next = nn; 18 | n->next = nn->next; 19 | nn->next = n; 20 | p = p->next->next; 21 | } 22 | 23 | return dummy.next; 24 | } 25 | }; 26 | 27 | int main() { 28 | Solution sln; 29 | 30 | ListNode* n1 = createListNode(vector({1, 2, 3, 4})); 31 | 32 | n1 = sln.swapPairs(n1); 33 | 34 | printListNode(n1); 35 | 36 | return 0; 37 | } -------------------------------------------------------------------------------- /word-break.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | bool wordBreak(string s, set &dict) { 6 | int len = (int)s.size(); 7 | vector words(len + 1, false); 8 | words[0] = true; 9 | 10 | for(int i = 1; i <= len; i++) { 11 | for(int j = i - 1; j >= 0; j--) { 12 | if(words[j] && dict.find(s.substr(j, i - j)) != dict.end()) { 13 | words[i] = true; 14 | break; 15 | } 16 | } 17 | } 18 | return words[len]; 19 | } 20 | }; 21 | 22 | int main() { 23 | Solution sln; 24 | set dict; 25 | dict.insert("leet"); 26 | dict.insert("code"); 27 | 28 | cout << sln.wordBreak("leetcode", dict) << endl; 29 | cout << sln.wordBreak("leetecode", dict) << endl; 30 | return 0; 31 | } -------------------------------------------------------------------------------- /anagrams.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | vector anagrams(vector &strs) { 6 | unordered_map m; 7 | vector r; 8 | if(strs.size() <= 1) { 9 | return r; 10 | } 11 | 12 | for(int i = 0; i < strs.size(); i++) { 13 | string s = strs[i]; 14 | sort(s.begin(), s.end()); 15 | 16 | auto it = m.find(s); 17 | if(it == m.end()) { 18 | m.insert(make_pair(s, i)); 19 | } else { 20 | if(it->second >= 0) { 21 | r.push_back(strs[it->second]); 22 | it->second = -1; 23 | } 24 | r.push_back(strs[i]); 25 | } 26 | } 27 | return r; 28 | } 29 | }; 30 | 31 | int main() { 32 | return 0; 33 | } -------------------------------------------------------------------------------- /longest-valid-parentheses.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int longestValidParentheses(string s) { 6 | int maxSum = 0; 7 | int i = 0; 8 | int len = s.size(); 9 | vector v; 10 | while(i < len) { 11 | if(s[i] == '(') { 12 | v.push_back(i); 13 | } else { 14 | if(!v.empty() && s[v.back()] == '(') { 15 | v.pop_back(); 16 | maxSum = max(maxSum, i - (v.empty() ? -1 : v.back())); 17 | } else { 18 | v.push_back(i); 19 | } 20 | } 21 | i++; 22 | } 23 | 24 | return maxSum; 25 | } 26 | }; 27 | 28 | int main() { 29 | Solution sln; 30 | 31 | cout << sln.longestValidParentheses("()(())") << endl; 32 | 33 | return 0; 34 | } -------------------------------------------------------------------------------- /pascals-triangle.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | vector > generate(int numRows) { 6 | vector > vals; 7 | vals.resize(numRows); 8 | 9 | for(int i = 0; i < numRows; i++) { 10 | vals[i].resize(i + 1); 11 | vals[i][0] = 1; 12 | vals[i][vals[i].size() - 1] = 1; 13 | for(int j = 1; j < vals[i].size() - 1; j++) { 14 | vals[i][j] = vals[i - 1][j - 1] + vals[i - 1][j]; 15 | } 16 | } 17 | 18 | return vals; 19 | } 20 | }; 21 | 22 | int main() { 23 | Solution sln; 24 | 25 | auto a = sln.generate(5); 26 | for(int i = 0; i < a.size(); i++) { 27 | for(int j = 0; j < a[i].size(); j++) { 28 | cout << a[i][j] << "\t"; 29 | } 30 | cout << endl; 31 | } 32 | 33 | return 0; 34 | } -------------------------------------------------------------------------------- /trapping-rain-water.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int trap(int A[], int n) { 6 | if(n == 0) { 7 | return 0; 8 | } 9 | int maxL[n]; 10 | int maxR[n]; 11 | maxL[0] = A[0]; 12 | for(int i = 1; i < n; i++) { 13 | maxL[i] = max(maxL[i - 1], A[i]); 14 | } 15 | 16 | maxR[n - 1] = A[n - 1]; 17 | for(int i = n - 2; i >= 0; i--) { 18 | maxR[i] = max(maxR[i + 1], A[i]); 19 | } 20 | 21 | int sum = 0; 22 | for(int i = 1; i < n - 1; i++) { 23 | sum += min(maxL[i], maxR[i]) - A[i]; 24 | } 25 | 26 | return sum; 27 | } 28 | }; 29 | 30 | int main() { 31 | Solution sln; 32 | int a[] = {5,5,1,7,1,1,5,2,7,6}; 33 | int n = sizeof(a) / sizeof(int); 34 | 35 | cout << sln.trap(a, n) << endl; 36 | return 0; 37 | } -------------------------------------------------------------------------------- /linked-list-cycle.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | bool hasCycle(ListNode *head) { 6 | if(head == NULL || head->next == NULL) { 7 | return false; 8 | } 9 | 10 | ListNode* fast = head; 11 | ListNode* slow = head; 12 | 13 | while(fast->next != NULL && fast->next->next != NULL) { 14 | fast = fast->next->next; 15 | slow = slow->next; 16 | if(slow == fast) { 17 | return true; 18 | } 19 | } 20 | 21 | return false; 22 | } 23 | }; 24 | 25 | int main() { 26 | ListNode n1(1); 27 | ListNode n2(2); 28 | ListNode n3(3); 29 | ListNode n4(4); 30 | 31 | n1.next = &n2; 32 | n2.next = &n3; 33 | n3.next = &n4; 34 | n4.next = &n1; 35 | 36 | Solution sln; 37 | 38 | cout << sln.hasCycle(&n1) << endl; 39 | 40 | return 0; 41 | } -------------------------------------------------------------------------------- /zigzag-conversion.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | string convert(string s, int nRows) { 6 | string r; 7 | int n = 2 * nRows - 2; 8 | if(nRows <= 1) { 9 | return s; 10 | } 11 | 12 | for(int i = 0; i < nRows; i++) { 13 | for(int j = 0, index = i; index < s.size(); 14 | j++, index = n * j + i) { 15 | r.append(1, s[index]); 16 | if(i == 0 || i == nRows - 1) { 17 | continue; 18 | } 19 | 20 | if(index + (nRows - i - 1) * 2 < s.size()) { 21 | r.append(1, s[index + (nRows - i - 1) * 2]); 22 | } 23 | } 24 | } 25 | return r; 26 | } 27 | }; 28 | 29 | int main() { 30 | Solution sln; 31 | cout << sln.convert("PAYPALISHIRING", 3) << endl; 32 | return 0; 33 | } -------------------------------------------------------------------------------- /add-binary.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | string addBinary(string a, string b) { 6 | string c; 7 | 8 | if(a.size() > b.size()) { 9 | b = b.insert(0, a.size() - b.size(), '0'); 10 | } else if(a.size() < b.size()) { 11 | a = a.insert(0, b.size() - a.size(), '0'); 12 | } 13 | 14 | int cnt = 0; 15 | for(int i = a.size() - 1; i >= 0; i--) { 16 | int val = cnt + a[i] + b[i] - '0' - '0'; 17 | c.push_back(val % 2 + '0'); 18 | cnt = val / 2; 19 | } 20 | 21 | while(cnt > 0) { 22 | c.push_back(cnt % 2 + '0'); 23 | cnt = cnt / 2; 24 | } 25 | 26 | reverse(c.begin(), c.end()); 27 | return c; 28 | } 29 | }; 30 | 31 | int main() { 32 | Solution sln; 33 | 34 | cout << sln.addBinary("11", "1") << endl; 35 | return 0; 36 | } -------------------------------------------------------------------------------- /partition-list.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | ListNode *partition(ListNode *head, int x) { 6 | ListNode dummy1(0), dummy2(0); 7 | ListNode* p1 = &dummy1; 8 | ListNode* p2 = &dummy2; 9 | 10 | ListNode* p = head; 11 | while(p) { 12 | if(p->val < x) { 13 | p1->next = p; 14 | p1 = p1->next; 15 | } else { 16 | p2->next = p; 17 | p2 = p2->next; 18 | } 19 | p = p->next; 20 | } 21 | 22 | p2->next = NULL; 23 | p1->next = dummy2.next; 24 | return dummy1.next; 25 | } 26 | }; 27 | 28 | int main() { 29 | Solution sln; 30 | 31 | ListNode* n1 = createListNode( 32 | vector({1, 4, 3, 2, 5, 2})); 33 | 34 | n1 = sln.partition(n1, 3); 35 | 36 | printListNode(n1); 37 | 38 | return 0; 39 | } -------------------------------------------------------------------------------- /sort-colors.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | void sortColors(int A[], int n) { 6 | if(n == 0) { 7 | return; 8 | } 9 | 10 | int red = 0; 11 | int blue = n - 1; 12 | int i = 0; 13 | while(i < blue + 1) { 14 | if(A[i] == 0) { 15 | swap(A[i], A[red]); 16 | red++; 17 | } else if(A[i] == 2) { 18 | swap(A[i], A[blue]); 19 | blue--; 20 | continue; 21 | } 22 | i++; 23 | } 24 | } 25 | }; 26 | 27 | int main() { 28 | int a[] = {2, 1, 0, 1, 1, 2, 2, 0, 0}; 29 | 30 | Solution sln; 31 | sln.sortColors(a, sizeof(a) / sizeof(int)); 32 | 33 | for(int i = 0; i < sizeof(a) / sizeof(int); i++) { 34 | cout << a[i] << "\t"; 35 | } 36 | 37 | cout << endl; 38 | 39 | return 0; 40 | } -------------------------------------------------------------------------------- /search-insert-position.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int searchInsert(int A[], int n, int target) { 6 | int l = 0; 7 | int h = n - 1; 8 | 9 | while(l <= h) { 10 | int mid = (l + h) / 2; 11 | if(A[mid] == target) { 12 | return mid; 13 | } 14 | 15 | if(A[mid] < target) { 16 | l = mid + 1; 17 | } else { 18 | h = mid - 1; 19 | } 20 | } 21 | 22 | return l; 23 | } 24 | }; 25 | 26 | int main() { 27 | Solution sln; 28 | int a[] = {1, 3, 5, 6}; 29 | int n = sizeof(a) / sizeof(int); 30 | 31 | cout << sln.searchInsert(a, n, 5) << endl; 32 | cout << sln.searchInsert(a, n, 2) << endl; 33 | cout << sln.searchInsert(a, n, 7) << endl; 34 | cout << sln.searchInsert(a, n, 0) << endl; 35 | 36 | 37 | 38 | return 0; 39 | } -------------------------------------------------------------------------------- /binary-tree-zigzag-level-order-traversal.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | vector > vals; 6 | vector > zigzagLevelOrder(TreeNode *root) { 7 | build(root, 1); 8 | 9 | for(int i = 1; i < vals.size(); i+=2) { 10 | reverse(vals[i].begin(), vals[i].end()); 11 | } 12 | 13 | return vals; 14 | } 15 | 16 | void build(TreeNode* node, int level) { 17 | if(!node) { 18 | return; 19 | } 20 | 21 | if(vals.size() <= level - 1) { 22 | vals.push_back(vector()); 23 | } 24 | 25 | vals[level - 1].push_back(node->val); 26 | 27 | if(node->left) { 28 | build(node->left, level + 1); 29 | } 30 | 31 | if(node->right) { 32 | build(node->right, level + 1); 33 | } 34 | } 35 | }; 36 | 37 | int main() { 38 | return 0; 39 | } -------------------------------------------------------------------------------- /same-tree.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | bool isSameTree(TreeNode *p, TreeNode *q) { 6 | return check(p, q); 7 | } 8 | 9 | bool check(TreeNode* p, TreeNode* q) { 10 | if(p == NULL) { 11 | return q == NULL; 12 | } else if(q == NULL) { 13 | return p == NULL; 14 | } else if(p->val != q->val) { 15 | return false; 16 | } 17 | 18 | return check(p->left, q->left) && check(p->right, q->right); 19 | } 20 | }; 21 | 22 | int main() { 23 | TreeNode n1(1); 24 | TreeNode n2(2); 25 | TreeNode n3(2); 26 | 27 | 28 | n1.left = &n2; 29 | n1.right = &n3; 30 | 31 | TreeNode n4(1); 32 | TreeNode n5(2); 33 | TreeNode n6(2); 34 | 35 | 36 | n4.left = &n5; 37 | n4.right = &n6; 38 | 39 | Solution sln; 40 | 41 | cout << sln.isSameTree(&n1, &n4) << endl; 42 | 43 | return 0; 44 | } -------------------------------------------------------------------------------- /symmetric-tree.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | bool isSymmetric(TreeNode *root) { 6 | if(!root) { 7 | return true; 8 | } 9 | 10 | return check(root->left, root->right); 11 | } 12 | 13 | bool check(TreeNode* left, TreeNode* right) { 14 | if(left == NULL) { 15 | return right == NULL; 16 | } else if(right == NULL) { 17 | return left == NULL; 18 | } else if(left->val != right->val) { 19 | return false; 20 | } 21 | 22 | return check(left->left, right->right) && check(left->right, right->left); 23 | } 24 | 25 | }; 26 | 27 | int main() { 28 | TreeNode n1(1); 29 | TreeNode n2(2); 30 | TreeNode n3(2); 31 | 32 | 33 | n1.left = &n2; 34 | n1.right = &n3; 35 | 36 | 37 | Solution sln; 38 | 39 | cout << sln.isSymmetric(&n1) << endl; 40 | 41 | return 0; 42 | } -------------------------------------------------------------------------------- /count-and-say.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | string countAndSay(int n) { 6 | string s = "1"; 7 | for(int i = 0; i < n - 1; i++) { 8 | s = gen(s); 9 | } 10 | return s; 11 | } 12 | 13 | string gen(string s) { 14 | string n; 15 | int len = s.size(); 16 | int i = 0; 17 | while(i < len) { 18 | char c = s[i]; 19 | char count = 1; 20 | while(i + count < len) { 21 | if(s[i + count] == c) { 22 | count++; 23 | } else { 24 | break; 25 | } 26 | } 27 | n.append(1, '0' + count); 28 | n.append(1, c); 29 | i += count; 30 | } 31 | return n; 32 | } 33 | }; 34 | 35 | int main() { 36 | Solution sln; 37 | cout << sln.countAndSay(10) << endl; 38 | return 0; 39 | } -------------------------------------------------------------------------------- /distinct-subsequences.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int numDistinct(string S, string T) { 6 | int m = S.size(); 7 | int n = T.size(); 8 | 9 | if(m == 0) { 10 | return 0; 11 | } else if(n == 0) { 12 | return 1; 13 | } 14 | 15 | vector > dp; 16 | dp.resize(m + 1); 17 | for(int i = 0; i < m + 1; i++) { 18 | dp[i].resize(n + 1); 19 | dp[i][0] = 1; 20 | } 21 | 22 | for(int i = 1; i < m + 1; i++) { 23 | for(int j = 1; j < n + 1; j++) { 24 | if(S[i - 1] == T[j - 1]) { 25 | dp[i][j] = dp[i -1][j - 1] + dp[i - 1][j]; 26 | } else { 27 | dp[i][j] = dp[i -1][j]; 28 | } 29 | } 30 | } 31 | 32 | return dp[m][n]; 33 | } 34 | }; 35 | 36 | int main() { 37 | return 0; 38 | } -------------------------------------------------------------------------------- /longest-substring-without-repeating-characters.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int lengthOfLongestSubstring(string s) { 6 | vector pos(256, -1); 7 | int start = 0; 8 | int maxV = numeric_limits::min(); 9 | for(int i = 0; i < s.size(); i++) { 10 | if(pos[s[i]] != -1) { 11 | maxV = max(maxV, i - start); 12 | start = pos[s[i]] + 1; 13 | i = pos[s[i]]; 14 | pos.clear(); 15 | pos.resize(256, -1); 16 | continue; 17 | } 18 | 19 | pos[s[i]] = i; 20 | } 21 | 22 | maxV = max(maxV, (int)s.size() - start); 23 | 24 | return maxV; 25 | } 26 | }; 27 | 28 | int main() { 29 | Solution sln; 30 | 31 | cout << sln.lengthOfLongestSubstring("wlrbbmqbhcdarzowkkyhiddqscdxrjmowfrxsjybldbefsarcbynecdyggxxpklorellnmpapqfwkhopkmco") << endl; 32 | return 0; 33 | } -------------------------------------------------------------------------------- /two-sum.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | vector twoSum(vector &numbers, int target) { 6 | unordered_map m; 7 | for(int i = 0; i < numbers.size(); i++) { 8 | m[numbers[i]] = i; 9 | } 10 | 11 | int index1, index2; 12 | 13 | for(int i = 0; i < numbers.size(); i++) { 14 | auto it = m.find(target - numbers[i]); 15 | if(it != m.end() && it->second != i) { 16 | index1 = min(i, it->second); 17 | index2 = max(i, it->second); 18 | break; 19 | } 20 | } 21 | 22 | return vector({index1 + 1, index2 + 1}); 23 | } 24 | }; 25 | 26 | int main() { 27 | Solution sln; 28 | 29 | vector n({2, 7, 11, 15}); 30 | 31 | auto v = sln.twoSum(n, 9); 32 | for(int i = 0; i < v.size(); i++) { 33 | cout << v[i] << "\t"; 34 | } 35 | cout << endl; 36 | return 0; 37 | } -------------------------------------------------------------------------------- /unique-binary-search-trees-ii.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | vector generateTrees(int n) { 6 | return generate(1, n); 7 | } 8 | 9 | vector generate(int start, int stop){ 10 | vector vs; 11 | if(start > stop) { 12 | vs.push_back(NULL); 13 | return vs; 14 | } 15 | 16 | for(int i = start; i <= stop; i++) { 17 | auto l = generate(start, i - 1); 18 | auto r = generate(i + 1, stop); 19 | 20 | for(int j = 0; j < l.size(); j++) { 21 | for(int k = 0; k < r.size(); k++) { 22 | TreeNode* n = new TreeNode(i); 23 | n->left = l[j]; 24 | n->right = r[k]; 25 | vs.push_back(n); 26 | } 27 | } 28 | } 29 | 30 | return vs; 31 | } 32 | }; 33 | 34 | int main() { 35 | return 0; 36 | } -------------------------------------------------------------------------------- /string-to-integer-atoi.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int atoi(const char *str) { 6 | if(!str) { 7 | return 0; 8 | } 9 | 10 | long long res = 0; 11 | while(isspace(*str)) { 12 | str++; 13 | } 14 | 15 | bool neg = (*str == '-'); 16 | if(*str == '-' || *str == '+') { 17 | str++; 18 | } 19 | 20 | while(isdigit(*str)) { 21 | int d = *str - '0'; 22 | res = res * 10 + d; 23 | if(!neg && res > INT_MAX) { 24 | return INT_MAX; 25 | } else if(neg && -res < INT_MIN) { 26 | return INT_MIN; 27 | } 28 | 29 | str++; 30 | } 31 | 32 | return neg ? -res : res; 33 | } 34 | }; 35 | 36 | int main() { 37 | Solution sln; 38 | 39 | cout << sln.atoi("123") << endl; 40 | cout << sln.atoi("-123") << endl; 41 | 42 | return 0; 43 | } -------------------------------------------------------------------------------- /candy.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int candy(vector &ratings) { 6 | vector candys; 7 | candys.resize(ratings.size(), 1); 8 | for(int i = 1; i < (int)ratings.size(); i++) { 9 | if(ratings[i] > ratings[i - 1]) { 10 | candys[i] = candys[i - 1] + 1; 11 | } 12 | } 13 | 14 | for(int i = (int)ratings.size() - 2; i >= 0; i--) { 15 | if(ratings[i] > ratings[i + 1] && candys[i] <= candys[i + 1]) { 16 | candys[i] = candys[i + 1] + 1; 17 | } 18 | } 19 | 20 | int n = 0; 21 | for(int i = 0; i < (int)candys.size(); i++) { 22 | n += candys[i]; 23 | } 24 | 25 | return n; 26 | } 27 | }; 28 | 29 | int main() { 30 | Solution sln; 31 | 32 | vector ratings; 33 | 34 | ratings.push_back(0); 35 | 36 | 37 | cout << sln.candy(ratings) << endl; 38 | 39 | return 0; 40 | } -------------------------------------------------------------------------------- /minimum-path-sum.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int minPathSum(vector > &grid) { 6 | if(grid.empty() || grid[0].empty()) { 7 | return 0; 8 | } 9 | 10 | int row = grid.size(); 11 | int col = grid[0].size(); 12 | 13 | int dp[row][col]; 14 | 15 | for(int i = 0; i < row; i++) { 16 | for(int j = 0; j < col; j++) { 17 | if(i == 0 && j == 0) { 18 | dp[i][j] = grid[0][0]; 19 | } else if(j == 0) { 20 | dp[i][0] = dp[i - 1][0] + grid[i][0]; 21 | } else if(i == 0) { 22 | dp[0][j] = dp[0][j - 1] + grid[0][j]; 23 | } else { 24 | dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j]; 25 | } 26 | } 27 | } 28 | 29 | return dp[row - 1][col - 1]; 30 | } 31 | }; 32 | 33 | int main() { 34 | return 0; 35 | } -------------------------------------------------------------------------------- /path-sum.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | bool hasPathSum(TreeNode *root, int sum) { 6 | if(!root) { 7 | return false; 8 | } 9 | 10 | if(!root->left && !root->right && root->val == sum) { 11 | return true; 12 | } 13 | 14 | return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val); 15 | } 16 | }; 17 | 18 | int main() { 19 | TreeNode n1(5); 20 | TreeNode n2(4); 21 | TreeNode n3(8); 22 | TreeNode n4(11); 23 | TreeNode n5(13); 24 | TreeNode n6(4); 25 | TreeNode n7(7); 26 | TreeNode n8(2); 27 | TreeNode n9(1); 28 | 29 | n1.left = &n2; 30 | n1.right = &n3; 31 | 32 | n2.left = &n4; 33 | n4.left = &n7; 34 | n4.right = &n8; 35 | 36 | n3.left = &n5; 37 | n3.right = &n6; 38 | 39 | n6.right = &n9; 40 | 41 | Solution sln; 42 | 43 | cout << sln.hasPathSum(&n1, 22) << endl; 44 | 45 | return 0; 46 | } -------------------------------------------------------------------------------- /roman-to-integer.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int toNumber(char c) { 6 | switch(c) { 7 | case 'I': 8 | return 1; 9 | case 'V': 10 | return 5; 11 | case 'X': 12 | return 10; 13 | case 'L': 14 | return 50; 15 | case 'C': 16 | return 100; 17 | case 'D': 18 | return 500; 19 | case 'M': 20 | return 1000; 21 | } 22 | return 0; 23 | } 24 | 25 | int romanToInt(string s) { 26 | int res = 0; 27 | for(int i = 0; i < s.size(); i++) { 28 | if(i > 0 && toNumber(s[i]) > toNumber(s[i - 1])) { 29 | res += toNumber(s[i]) - 2 * toNumber(s[i - 1]); 30 | } else { 31 | res += toNumber(s[i]); 32 | } 33 | } 34 | 35 | return res; 36 | } 37 | }; 38 | 39 | int main() { 40 | return 0; 41 | } -------------------------------------------------------------------------------- /remove-nth-node-from-end-of-list.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | ListNode *removeNthFromEnd(ListNode *head, int n) { 6 | if(!head) { 7 | return head; 8 | } 9 | 10 | ListNode* p1 = head; 11 | ListNode* p2 = head; 12 | 13 | for(int i = 0; i < n; i++) { 14 | p1 = p1->next; 15 | } 16 | 17 | if(!p1) { 18 | head = head->next; 19 | return head; 20 | } 21 | 22 | while(p1->next) { 23 | p1 = p1->next; 24 | p2 = p2->next; 25 | } 26 | 27 | p2->next = p2->next->next; 28 | 29 | return head; 30 | } 31 | }; 32 | 33 | int main() { 34 | Solution sln; 35 | ListNode* n1 = createListNode(vector({1, 2, 3, 4, 5})); 36 | n1 = sln.removeNthFromEnd(n1, 2); 37 | printListNode(n1); 38 | 39 | ListNode* n2 = createListNode(vector({1})); 40 | n2 = sln.removeNthFromEnd(n2, 1); 41 | printListNode(n2); 42 | 43 | return 0; 44 | } -------------------------------------------------------------------------------- /spiral-matrix-ii.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | vector > generateMatrix(int n) { 6 | vector > v(n, vector(n, 0)); 7 | 8 | int a = n; 9 | int val = 1; 10 | for(int i = 0; i < n / 2; i++, a -= 2) { 11 | for(int c = i; c < i + a; c++) { 12 | v[i][c] = val++; 13 | } 14 | 15 | for(int r = i + 1; r < i + a; r++) { 16 | v[r][i + a - 1] = val++; 17 | } 18 | 19 | for(int c = i + a - 2; c >= i; c--) { 20 | v[i + a - 1][c] = val++; 21 | } 22 | 23 | for(int r = i + a - 2; r > i; r--) { 24 | v[r][i] = val++; 25 | } 26 | } 27 | 28 | if(n % 2) { 29 | v[n / 2][n / 2] = val; 30 | } 31 | 32 | return v; 33 | } 34 | }; 35 | 36 | int main() { 37 | Solution sln; 38 | 39 | auto a = sln.generateMatrix(3); 40 | 41 | printVector2(a); 42 | 43 | return 0; 44 | } -------------------------------------------------------------------------------- /generate-parentheses.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | vector v; 6 | 7 | vector generateParenthesis(int n) { 8 | 9 | string s; 10 | 11 | dfs(n, n, s); 12 | 13 | return v; 14 | } 15 | 16 | void dfs(int left, int right, string& s) { 17 | if(left > right) { 18 | return; 19 | } 20 | 21 | if(left == 0 && right == 0) { 22 | v.push_back(s); 23 | return; 24 | } 25 | 26 | if(left > 0) { 27 | int l = s.size(); 28 | s.append("(", 1); 29 | dfs(left - 1, right, s); 30 | s.erase(l); 31 | } 32 | 33 | if(right > 0) { 34 | int l = s.size(); 35 | s.append(")", 1); 36 | dfs(left, right - 1, s); 37 | s.erase(l); 38 | } 39 | } 40 | }; 41 | 42 | int main() { 43 | Solution sln; 44 | 45 | auto a = sln.generateParenthesis(3); 46 | 47 | printVector(a); 48 | 49 | return 0; 50 | } -------------------------------------------------------------------------------- /binary-tree-maximum-path-sum.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int maxPathSum(TreeNode *root) { 6 | int maxSum = numeric_limits::min(); 7 | int sum = getMax(root, maxSum); 8 | return max(sum, maxSum); 9 | } 10 | 11 | int getMax(TreeNode* node, int &sum) { 12 | if(!node) { 13 | return 0; 14 | } 15 | 16 | int left = getMax(node->left, sum); 17 | int right = getMax(node->right, sum); 18 | 19 | int val = node->val; 20 | 21 | if(left > 0) { 22 | val += left; 23 | } 24 | if(right > 0) { 25 | val += right; 26 | } 27 | 28 | sum = std::max(sum, val); 29 | return max(node->val, max(node->val + left, node->val + right)); 30 | } 31 | }; 32 | 33 | int main() { 34 | TreeNode n1(1); 35 | TreeNode n2(2); 36 | TreeNode n3(3); 37 | 38 | n1.left = &n2; 39 | n1.right = &n3; 40 | 41 | Solution sln; 42 | 43 | cout << sln.maxPathSum(&n1) << endl; 44 | 45 | return 0; 46 | } -------------------------------------------------------------------------------- /n-queens-ii.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int num; 6 | int totalNQueens(int n) { 7 | vector pos; 8 | 9 | num = 0; 10 | dfs(pos, 0, n); 11 | 12 | return num; 13 | } 14 | 15 | void dfs(vector &pos, int k, int n) { 16 | if(n == k) { 17 | num++; 18 | return; 19 | } 20 | 21 | for(int i = 0; i < n; i++) { 22 | if(isValid(pos, k, i)) { 23 | pos.push_back(i); 24 | dfs(pos, k + 1, n); 25 | pos.pop_back(); 26 | } 27 | } 28 | } 29 | 30 | bool isValid(vector &pos, int row, int col) { 31 | for(int j = 0; j < pos.size(); j++) { 32 | if(pos[j] == col || abs(j - row) == abs(pos[j] - col)) { 33 | return false; 34 | } 35 | } 36 | return true; 37 | } 38 | }; 39 | 40 | int main() { 41 | Solution sln; 42 | 43 | auto a = sln.totalNQueens(4); 44 | 45 | cout << a << endl; 46 | 47 | return 0; 48 | } -------------------------------------------------------------------------------- /remove-duplicates-from-sorted-list.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | ListNode *deleteDuplicates(ListNode *head) { 6 | if(!head) { 7 | return head; 8 | } 9 | 10 | int val = head->val; 11 | ListNode* p = head; 12 | while(p && p->next) { 13 | if(p->next->val != val) { 14 | val = p->next->val; 15 | p = p->next; 16 | } else { 17 | ListNode* n = p->next->next; 18 | p->next = n; 19 | } 20 | } 21 | 22 | return head; 23 | } 24 | }; 25 | 26 | 27 | 28 | int main() { 29 | Solution sln; 30 | ListNode* n1 = createListNode(vector({1, 1, 2})); 31 | n1 = sln.deleteDuplicates(n1); 32 | printListNode(n1); 33 | 34 | n1 = createListNode(vector({1, 1, 2, 3, 3})); 35 | n1 = sln.deleteDuplicates(n1); 36 | printListNode(n1); 37 | 38 | n1 = createListNode(vector({1, 1, 1})); 39 | n1 = sln.deleteDuplicates(n1); 40 | printListNode(n1); 41 | return 0; 42 | } -------------------------------------------------------------------------------- /search-in-rotated-sorted-array.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int search(int A[], int n, int target) { 6 | int l = 0; 7 | int h = n - 1; 8 | while(l <= h) { 9 | int m = (l + h) / 2; 10 | if(A[m] == target) { 11 | return m; 12 | } 13 | 14 | if(A[m] >= A[l]) { 15 | if(A[l] <= target && target < A[m]) { 16 | h = m - 1; 17 | } else { 18 | l = m + 1; 19 | } 20 | } else { 21 | if(A[h] >= target && target > A[m]) { 22 | l = m + 1; 23 | } else { 24 | h = m - 1; 25 | } 26 | } 27 | } 28 | return -1; 29 | } 30 | }; 31 | 32 | int main() { 33 | Solution sln; 34 | 35 | int a[] = {3, 1}; 36 | 37 | int n = sizeof(a) / sizeof(int); 38 | 39 | cout << sln.search(a, n, 3) << endl; 40 | cout << sln.search(a, n, 1) << endl; 41 | 42 | return 0; 43 | } -------------------------------------------------------------------------------- /decode-ways.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int numDecodings(string s) { 6 | int n = s.size(); 7 | if(n == 0) { 8 | return 0; 9 | } 10 | vector dp(n + 1, 0); 11 | dp[0] = 1; 12 | if(isValid(s[0])) { 13 | dp[1] = 1; 14 | } 15 | 16 | for(int i = 2; i <= n; i++) { 17 | if(isValid(s[i - 1])) { 18 | dp[i] = dp[i - 1]; 19 | } 20 | if(isValid(s[i - 2], s[i - 1])) { 21 | dp[i] += dp[i - 2]; 22 | } 23 | } 24 | 25 | return dp[n]; 26 | } 27 | 28 | bool isValid(char c) { 29 | return c != '0'; 30 | } 31 | 32 | bool isValid(char c1, char c2) { 33 | if(c1 == '1') { 34 | return true; 35 | } else if(c1 == '2') { 36 | return c2 >= '0' && c2 <= '6'; 37 | } else { 38 | return false; 39 | } 40 | } 41 | }; 42 | 43 | int main() { 44 | Solution sln; 45 | cout << sln.numDecodings("10") << endl; 46 | return 0; 47 | } -------------------------------------------------------------------------------- /longest-common-prefix.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | string longestCommonPrefix(vector &strs) { 6 | string s; 7 | if(strs.empty()) { 8 | return s; 9 | } 10 | 11 | int pos = 0; 12 | char c; 13 | 14 | while(1) { 15 | for(int i = 0; i < strs.size(); i++) { 16 | if(i == 0) { 17 | if(strs[0].size() > pos) { 18 | c = strs[0][pos]; 19 | } else { 20 | return s; 21 | } 22 | } else { 23 | if(strs[i].size() == pos || strs[i][pos] != c) { 24 | return s; 25 | } 26 | } 27 | } 28 | 29 | pos++; 30 | s.append(1, c); 31 | 32 | } 33 | return s; 34 | } 35 | }; 36 | 37 | int main() { 38 | Solution sln; 39 | 40 | vector strs({"abcde", "abcd"}); 41 | 42 | cout << sln.longestCommonPrefix(strs) << endl; 43 | 44 | return 0; 45 | } -------------------------------------------------------------------------------- /combination-sum.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | vector > vv; 6 | vector > combinationSum(vector &candidates, int target) { 7 | sort(candidates.begin(), candidates.end()); 8 | vector v; 9 | dfs(v, candidates, target); 10 | return vv; 11 | } 12 | 13 | void dfs(vector& v, vector &candidates, int target) { 14 | if(target == 0) { 15 | vv.push_back(v); 16 | return; 17 | } else if(target < 0) { 18 | return; 19 | } 20 | 21 | for(int i = 0; i < candidates.size(); i++) { 22 | if(!v.empty() && v.back() > candidates[i]) { 23 | continue; 24 | } 25 | v.push_back(candidates[i]); 26 | dfs(v, candidates, target - candidates[i]); 27 | v.pop_back(); 28 | } 29 | } 30 | }; 31 | 32 | int main() { 33 | Solution sln; 34 | 35 | vector c({2, 3, 6, 7}); 36 | 37 | auto vv = sln.combinationSum(c, 7); 38 | 39 | printVector2(vv); 40 | 41 | return 0; 42 | } -------------------------------------------------------------------------------- /edit-distance.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int minDistance(string word1, string word2) { 6 | int m = word1.size(); 7 | int n = word2.size(); 8 | 9 | if(m == 0) { 10 | return n; 11 | } else if(n == 0) { 12 | return m; 13 | } 14 | 15 | int dp[m + 1][n + 1]; 16 | 17 | for(int i = 0; i <= m; i++) { 18 | dp[i][0] = i; 19 | } 20 | 21 | for(int j = 0; j <= n; j++) { 22 | dp[0][j] = j; 23 | } 24 | 25 | 26 | for(int i = 1; i <= m; i++) { 27 | for(int j = 1; j <= n; j++) { 28 | if(word1[i - 1] == word2[j - 1]) { 29 | dp[i][j] = dp[i - 1][j - 1]; 30 | } else { 31 | dp[i][j] = min(min(dp[i][j - 1], dp[i - 1][j]), dp[i - 1][j - 1]) + 1; 32 | } 33 | } 34 | } 35 | 36 | return dp[m][n]; 37 | } 38 | }; 39 | 40 | int main() { 41 | Solution sln; 42 | 43 | cout << sln.minDistance("sea", "ate") << endl; 44 | 45 | return 0; 46 | } -------------------------------------------------------------------------------- /palindrome-partitioning-ii.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int minCut(string s) { 6 | if(s.empty()) { 7 | return 0; 8 | } 9 | 10 | vector > vv; 11 | vv.resize(s.size()); 12 | for(size_t i = 0; i < vv.size(); i++) { 13 | vv[i].resize(s.size(), false); 14 | } 15 | 16 | vector cuts; 17 | cuts.resize(s.size() + 1, 0); 18 | for(size_t i = 0; i < s.size(); i++) { 19 | cuts[i] = s.size() - i; 20 | } 21 | 22 | for(int i = (int)s.size() - 1; i >= 0; i--) { 23 | for(int j = i; j < (int)s.size(); j++) { 24 | if( (s[i] == s[j] && j - i < 2) || (s[i] == s[j] && vv[i + 1][j - 1])) { 25 | vv[i][j] = true; 26 | 27 | cuts[i] = min(cuts[i], cuts[j + 1] + 1); 28 | } 29 | } 30 | } 31 | 32 | return cuts[0] - 1; 33 | } 34 | }; 35 | 36 | int main() { 37 | Solution sln; 38 | 39 | cout << sln.minCut("aab") << endl; 40 | 41 | return 0; 42 | } -------------------------------------------------------------------------------- /permutations.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | vector > vv; 6 | vector visits; 7 | vector > permute(vector &num) { 8 | if(num.empty()) { 9 | return vv; 10 | } 11 | 12 | visits.resize(num.size(), false); 13 | 14 | vector v; 15 | dfs(v, num, 0); 16 | 17 | return vv; 18 | } 19 | 20 | void dfs(vector& v, vector& num, int step) { 21 | if(step == num.size()) { 22 | vv.push_back(v); 23 | return; 24 | } 25 | 26 | for(int i = 0; i < num.size(); i++) { 27 | if(!visits[i]) { 28 | visits[i] = true; 29 | 30 | v.push_back(num[i]); 31 | 32 | dfs(v, num, step + 1); 33 | 34 | v.pop_back(); 35 | visits[i] = false; 36 | } 37 | } 38 | } 39 | }; 40 | 41 | int main() { 42 | Solution sln; 43 | 44 | vector v({1, 2, 3}); 45 | auto a = sln.permute(v); 46 | 47 | printVector2(a); 48 | 49 | return 0; 50 | } -------------------------------------------------------------------------------- /linked-list-cycle-ii.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | ListNode *detectCycle(ListNode *head) { 6 | if(head == NULL || head->next == NULL) { 7 | return NULL; 8 | } 9 | 10 | ListNode* fast = head; 11 | ListNode* slow = head; 12 | 13 | while(fast->next != NULL && fast->next->next != NULL) { 14 | fast = fast->next->next; 15 | slow = slow->next; 16 | if(fast == slow) { 17 | slow = head; 18 | while(slow != fast) { 19 | fast = fast->next; 20 | slow = slow->next; 21 | } 22 | return slow; 23 | } 24 | } 25 | 26 | return NULL; 27 | } 28 | }; 29 | 30 | int main() { 31 | ListNode n1(1); 32 | ListNode n2(2); 33 | ListNode n3(3); 34 | ListNode n4(4); 35 | 36 | n1.next = &n2; 37 | n2.next = &n3; 38 | n3.next = &n4; 39 | n4.next = &n1; 40 | 41 | Solution sln; 42 | 43 | cout << &n1 << "\t" << sln.detectCycle(&n1) << endl; 44 | 45 | return 0; 46 | } -------------------------------------------------------------------------------- /merge-intervals.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | static bool comp(Interval a, Interval b) 6 | { 7 | return a.start < b.start; 8 | } 9 | 10 | vector merge(vector &intervals) { 11 | if(intervals.empty()) { 12 | return intervals; 13 | } 14 | 15 | sort(intervals.begin(), intervals.end(), comp); 16 | vector v; 17 | v.push_back(intervals[0]); 18 | 19 | for(int i = 1; i < intervals.size(); i++) { 20 | Interval& n1 = v.back(); 21 | Interval& n2 = intervals[i]; 22 | 23 | if((n1.start <= n2.start && n2.start <= n1.end) || 24 | (n2.start <= n1.start && n1.start <= n2.end)) { 25 | v.pop_back(); 26 | n1.start = min(n1.start, n2.start); 27 | n1.end = max(n1.end, n2.end); 28 | v.push_back(n1); 29 | } else { 30 | v.push_back(n2); 31 | } 32 | 33 | } 34 | 35 | return v; 36 | } 37 | }; 38 | 39 | int main() { 40 | return 0; 41 | } -------------------------------------------------------------------------------- /reverse-linked-list-ii.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | ListNode *reverseBetween(ListNode *head, int m, int n) { 6 | if(!head) { 7 | return head; 8 | } 9 | 10 | ListNode dummy(0); 11 | dummy.next = head; 12 | 13 | ListNode* p = &dummy; 14 | for(int i = 1; i < m; i++) { 15 | p = p->next; 16 | } 17 | 18 | ListNode* pm = p->next; 19 | 20 | for(int i = m; i < n; i++) { 21 | ListNode* n = pm->next; 22 | pm->next = n->next; 23 | n->next = p->next; 24 | p->next = n; 25 | } 26 | 27 | return dummy.next; 28 | } 29 | }; 30 | 31 | int main() { 32 | ListNode n1(1); 33 | ListNode n2(2); 34 | ListNode n3(3); 35 | ListNode n4(4); 36 | ListNode n5(5); 37 | 38 | n1.next = &n2; 39 | n2.next = &n3; 40 | n3.next = &n4; 41 | n4.next = &n5; 42 | 43 | printListNode(&n1); 44 | 45 | Solution sln; 46 | 47 | auto a = sln.reverseBetween(&n1, 2, 5); 48 | 49 | printListNode(&n1); 50 | 51 | return 0; 52 | } -------------------------------------------------------------------------------- /construct-binary-tree-from-preorder-and-inorder-traversal.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | unordered_map m; 6 | TreeNode *buildTree(vector &preorder, vector &inorder) { 7 | if(preorder.empty()) { 8 | return NULL; 9 | } 10 | 11 | for(int i = 0; i < inorder.size(); i++) { 12 | m[inorder[i]] = i; 13 | } 14 | 15 | return build(preorder, 0, preorder.size() - 1, inorder, 0, inorder.size() - 1); 16 | } 17 | 18 | TreeNode* build(vector& preorder, int s0, int e0, vector &inorder, int s1, int e1) { 19 | if(s0 > e0 || s1 > e1) { 20 | return NULL; 21 | } 22 | 23 | int mid = m[preorder[s0]]; 24 | 25 | TreeNode* root = new TreeNode(preorder[s0]); 26 | 27 | int num = mid - s1; 28 | 29 | root->left = build(preorder, s0 + 1, s0 + num, inorder, s1, mid - 1); 30 | root->right = build(preorder, s0 + num + 1, e0, inorder, mid + 1, e1); 31 | 32 | return root; 33 | } 34 | }; 35 | 36 | int main() { 37 | 38 | return 0; 39 | } -------------------------------------------------------------------------------- /insertion-sort-list.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | ListNode *insertionSortList(ListNode *head) { 6 | if(head == NULL || head->next == NULL) { 7 | return head; 8 | } 9 | 10 | ListNode dummy(0); 11 | 12 | ListNode* p = &dummy; 13 | 14 | ListNode* cur = head; 15 | while(cur) { 16 | p = &dummy; 17 | 18 | while(p->next && p->next->val <= cur->val) { 19 | p = p->next; 20 | } 21 | 22 | ListNode* n = p->next; 23 | p->next = cur; 24 | 25 | cur = cur->next; 26 | p->next->next = n; 27 | } 28 | 29 | return dummy.next; 30 | } 31 | }; 32 | 33 | int main() { 34 | ListNode n1(6); 35 | ListNode n2(1); 36 | ListNode n3(9); 37 | 38 | ListNode n4(2); 39 | ListNode n5(7); 40 | 41 | n1.next = &n2; 42 | n2.next = &n3; 43 | n3.next = &n4; 44 | n4.next = &n5; 45 | 46 | Solution sln; 47 | 48 | ListNode * a = sln.insertionSortList(&n1); 49 | 50 | printListNode(a); 51 | 52 | return 0; 53 | } -------------------------------------------------------------------------------- /clone-graph.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) { 6 | if(node == NULL) { 7 | return NULL; 8 | } 9 | 10 | UndirectedGraphNode dummy(0); 11 | 12 | map ns; 13 | clone(node, &dummy, ns); 14 | 15 | return dummy.neighbors[0]; 16 | } 17 | 18 | void clone(UndirectedGraphNode* srcNode, UndirectedGraphNode* p, map &ns) { 19 | map::iterator it = ns.find(srcNode); 20 | if(it != ns.end()) { 21 | p->neighbors.push_back(it->second); 22 | return; 23 | } 24 | UndirectedGraphNode* node = new UndirectedGraphNode(srcNode->label); 25 | p->neighbors.push_back(node); 26 | 27 | ns[srcNode] = node; 28 | 29 | for(size_t i = 0; i < srcNode->neighbors.size(); i++) { 30 | clone(srcNode->neighbors[i], node, ns); 31 | } 32 | } 33 | }; 34 | 35 | int main() { 36 | return 0; 37 | } -------------------------------------------------------------------------------- /scramble-string.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | bool isScramble(string s1, string s2) { 6 | if(s1.size() != s2.size()) { 7 | return false; 8 | } 9 | 10 | char v = 0; 11 | for(int i = 0; i < s1.size(); i++) { 12 | v ^= (s1[i] ^ s2[i]); 13 | } 14 | 15 | if(v != 0) { 16 | return false; 17 | } 18 | 19 | for(int i = 1; i < s1.size(); i++) { 20 | string s11 = s1.substr(0, i); 21 | string s12 = s1.substr(i, s1.size() - i); 22 | 23 | string s21 = s2.substr(0, i); 24 | string s22 = s2.substr(i, s1.size() - i); 25 | 26 | if(isScramble(s11, s21) && isScramble(s12, s22)) { 27 | return true; 28 | } 29 | 30 | s21 = s2.substr(s2.size() - i, i); 31 | s22 = s2.substr(0, s2.size() - i); 32 | 33 | if(isScramble(s11, s21) && isScramble(s12, s22)) { 34 | return true; 35 | } 36 | } 37 | 38 | return false; 39 | } 40 | }; 41 | 42 | int main() { 43 | return 0; 44 | } -------------------------------------------------------------------------------- /construct-binary-tree-from-inorder-and-postorder-traversal.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | unordered_map m; 6 | TreeNode *buildTree(vector &inorder, vector &postorder) { 7 | if(postorder.empty()) { 8 | return NULL; 9 | } 10 | 11 | for(int i = 0; i < inorder.size(); i++) { 12 | m[inorder[i]] = i; 13 | } 14 | 15 | return build(inorder, 0, inorder.size() - 1, 16 | postorder, 0, postorder.size() - 1); 17 | } 18 | 19 | TreeNode* build(vector& inorder, int s0, int e0, 20 | vector& postorder, int s1, int e1) { 21 | if(s0 > e0 || s1 > e1) { 22 | return NULL; 23 | } 24 | 25 | TreeNode* root = new TreeNode(postorder[e1]); 26 | 27 | int mid = m[postorder[e1]]; 28 | int num = mid - s0; 29 | 30 | root->left = build(inorder, s0, mid - 1, postorder, s1, s1 + num - 1); 31 | root->right = build(inorder, mid + 1, e0, postorder, s1 + num, e1 - 1); 32 | 33 | return root; 34 | } 35 | }; 36 | 37 | int main() { 38 | return 0; 39 | } -------------------------------------------------------------------------------- /search-in-rotated-sorted-array-ii.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int search(int A[], int n, int target) { 6 | int l = 0; 7 | int h = n - 1; 8 | while(l <= h) { 9 | int m = (l + h) / 2; 10 | if(A[m] == target) { 11 | return true; 12 | } 13 | 14 | if(A[m] > A[l]) { 15 | if(A[l] <= target && target < A[m]) { 16 | h = m - 1; 17 | } else { 18 | l = m + 1; 19 | } 20 | } else if(A[m] < A[l]){ 21 | if(A[h] >= target && target > A[m]) { 22 | l = m + 1; 23 | } else { 24 | h = m - 1; 25 | } 26 | } else { 27 | l++; 28 | } 29 | } 30 | return false; 31 | } 32 | }; 33 | 34 | int main() { 35 | Solution sln; 36 | 37 | int a[] = {1}; 38 | 39 | int n = sizeof(a) / sizeof(int); 40 | 41 | cout << sln.search(a, n, 0) << endl; 42 | cout << sln.search(a, n, 1) << endl; 43 | 44 | return 0; 45 | } -------------------------------------------------------------------------------- /subsets.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | vector > res; 6 | vector > subsets(vector &S) { 7 | if(S.empty()) { 8 | return res; 9 | } 10 | 11 | sort(S.begin(), S.end()); 12 | 13 | res.push_back(vector()); 14 | 15 | vector v; 16 | 17 | generate(0, v, S); 18 | 19 | return res; 20 | } 21 | 22 | void generate(int start, vector& v, vector &S) { 23 | if(start == S.size()) { 24 | return; 25 | } 26 | 27 | for(int i = start; i < S.size(); i++) { 28 | v.push_back(S[i]); 29 | 30 | res.push_back(v); 31 | 32 | generate(i + 1, v, S); 33 | 34 | v.pop_back(); 35 | } 36 | } 37 | }; 38 | 39 | int main() { 40 | Solution sln; 41 | vector s({1, 2, 3}); 42 | 43 | auto a = sln.subsets(s); 44 | 45 | for(int i = 0; i < a.size(); i++) { 46 | for(int j = 0; j < a[i].size(); j++) { 47 | cout << a[i][j] << "\t"; 48 | } 49 | cout << endl; 50 | } 51 | 52 | return 0; 53 | } -------------------------------------------------------------------------------- /merge-k-sorted-lists.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | ListNode *mergeKLists(vector &lists) { 6 | if(lists.empty()) { 7 | return NULL; 8 | } 9 | 10 | int n = lists.size(); 11 | while(n > 1) { 12 | int k = (n + 1) / 2; 13 | for(int i = 0; i < n / 2; i++) { 14 | lists[i] = merge2List(lists[i], lists[i + k]); 15 | } 16 | n = k; 17 | } 18 | return lists[0]; 19 | } 20 | 21 | ListNode* merge2List(ListNode* n1, ListNode* n2) { 22 | ListNode dummy(0); 23 | ListNode* p = &dummy; 24 | while(n1 && n2) { 25 | if(n1->val < n2->val) { 26 | p->next = n1; 27 | n1 = n1->next; 28 | } else { 29 | p->next = n2; 30 | n2 = n2->next; 31 | } 32 | p = p->next; 33 | } 34 | 35 | if(n1) { 36 | p->next = n1; 37 | } else if(n2) { 38 | p->next = n2; 39 | } 40 | 41 | return dummy.next; 42 | } 43 | }; 44 | 45 | int main() { 46 | return 0; 47 | } -------------------------------------------------------------------------------- /find-minimum-in-rotated-sorted-array.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int findMin(vector &num) { 6 | int size = num.size(); 7 | 8 | if(size == 0) { 9 | return 0; 10 | } else if(size == 1) { 11 | return num[0]; 12 | } else if(size == 2) { 13 | return min(num[0], num[1]); 14 | } 15 | 16 | int start = 0; 17 | int stop = size - 1; 18 | 19 | while(start < stop - 1) { 20 | if(num[start] < num[stop]) { 21 | return num[start]; 22 | } 23 | 24 | int mid = start + (stop - start) / 2; 25 | if(num[mid] > num[start]) { 26 | start = mid; 27 | } else if(num[mid] < num[start]) { 28 | stop = mid; 29 | } 30 | } 31 | 32 | return min(num[start], num[stop]); 33 | } 34 | }; 35 | 36 | int main() { 37 | Solution sln; 38 | 39 | vector v{1,2,3,4,5,6,7}; 40 | int m = sln.findMin(v); 41 | 42 | cout << m << endl; 43 | 44 | v = vector{4,5,6,7,0,1,2}; 45 | m = sln.findMin(v); 46 | 47 | cout << m << endl; 48 | return 0; 49 | } -------------------------------------------------------------------------------- /combination-sum-ii.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | vector > vv; 6 | vector > combinationSum2(vector &num, int target) { 7 | sort(num.begin(), num.end()); 8 | 9 | vector v; 10 | 11 | dfs(v, 0, num, target); 12 | return vv; 13 | } 14 | 15 | void dfs(vector& v, int level, vector& num, int target) { 16 | if(target == 0) { 17 | vv.push_back(v); 18 | return; 19 | } else if(target < 0) { 20 | return; 21 | } 22 | 23 | for(int i = level; i < num.size(); i++) { 24 | if(!v.empty() && v.back() > num[i]) { 25 | continue; 26 | } 27 | 28 | 29 | v.push_back(num[i]); 30 | dfs(v, i + 1, num, target - num[i]); 31 | v.pop_back(); 32 | 33 | while(i < num.size() - 1 && num[i] == num[i + 1]) { 34 | i++; 35 | } 36 | } 37 | } 38 | }; 39 | 40 | int main() { 41 | vector n({1, 2}); 42 | Solution sln; 43 | 44 | auto vv = sln.combinationSum2(n, 4); 45 | printVector2(vv); 46 | 47 | return 0; 48 | } -------------------------------------------------------------------------------- /intersection-of-two-linked-lists.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { 6 | if(!headA) { 7 | return NULL; 8 | } else if (!headB) { 9 | return NULL; 10 | } 11 | 12 | ListNode* p = headA; 13 | while(p->next) { 14 | p = p->next; 15 | } 16 | 17 | p->next = headB; 18 | 19 | //is this O(1)??? 20 | ListNode* tail = p; 21 | p = headA; 22 | 23 | headB = headA; 24 | while(headB->next && headB->next->next) { 25 | headA = headA->next; 26 | headB = headB->next->next; 27 | if(headA == headB) { 28 | break; 29 | } 30 | } 31 | 32 | if(!headA->next || !headB->next || !headB->next->next) { 33 | tail->next = NULL; 34 | return NULL; 35 | } 36 | 37 | headA = p; 38 | while(headA != headB) { 39 | headA = headA->next; 40 | headB = headB->next; 41 | } 42 | 43 | tail->next = NULL; 44 | return headA; 45 | } 46 | }; 47 | 48 | int main() { 49 | return 0; 50 | } -------------------------------------------------------------------------------- /binary-tree-inorder-traversal.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | vector inorderTraversal(TreeNode *root) { 6 | vector vals; 7 | if(root == NULL) { 8 | return vals; 9 | } 10 | 11 | vector nodes; 12 | TreeNode* p = root; 13 | while(p || !nodes.empty()) { 14 | while(p) { 15 | nodes.push_back(p); 16 | p = p->left; 17 | } 18 | 19 | if(!nodes.empty()) { 20 | p = nodes.back(); 21 | vals.push_back(p->val); 22 | nodes.pop_back(); 23 | p = p->right; 24 | } 25 | } 26 | 27 | return vals; 28 | } 29 | }; 30 | 31 | int main() { 32 | TreeNode n1(1); 33 | 34 | TreeNode n2(2); 35 | n1.right = &n2; 36 | 37 | TreeNode n3(3); 38 | n2.left = &n3; 39 | 40 | Solution sln; 41 | 42 | vector a = sln.inorderTraversal(&n1); 43 | for(int i = 0; i < a.size(); i++) { 44 | cout << a[i]; 45 | if(i != a.size() - 1) { 46 | cout << "\t"; 47 | } else { 48 | cout << endl; 49 | } 50 | } 51 | 52 | return 0; 53 | } -------------------------------------------------------------------------------- /maximum-subarray.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int maxSubArray(int A[], int n) { 6 | return divide(A, 0, n - 1, INT_MIN); 7 | } 8 | 9 | int divide(int A[], int left, int right, int tmax) { 10 | if(left > right) { 11 | return INT_MIN; 12 | } 13 | 14 | int mid = (left + right) / 2; 15 | int lmax = divide(A, left, mid - 1, tmax); 16 | int rmax = divide(A, mid + 1, right, tmax); 17 | 18 | tmax = max(tmax, lmax); 19 | tmax = max(tmax, rmax); 20 | 21 | int sum = 0; 22 | int mlmax = 0; 23 | for(int i = mid - 1; i >= left; i--) { 24 | sum += A[i]; 25 | mlmax = max(mlmax, sum); 26 | } 27 | 28 | sum = 0; 29 | int mrmax = 0; 30 | for(int i = mid + 1; i <= right; i++) { 31 | sum += A[i]; 32 | mrmax = max(mrmax, sum); 33 | } 34 | 35 | tmax = max(tmax, A[mid] + mlmax + mrmax); 36 | return tmax; 37 | } 38 | }; 39 | 40 | int main() { 41 | Solution sln; 42 | int a[] = {-2,1,-3,4,-1,2,1,-5,4}; 43 | int n = sizeof(a) / sizeof(int); 44 | 45 | cout << sln.maxSubArray(a, n) << endl; 46 | 47 | return 0; 48 | } -------------------------------------------------------------------------------- /multiply-strings.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | string multiply(string num1, string num2) { 6 | if(num1.empty() || num2.empty()) { 7 | return "0"; 8 | } 9 | 10 | reverse(num1.begin(), num1.end()); 11 | reverse(num2.begin(), num2.end()); 12 | 13 | string r(num1.size() + num2.size() + 1, '0'); 14 | 15 | 16 | for(int i = 0; i < num1.size(); i++) { 17 | int dig1 = num1[i] - '0'; 18 | int carry = 0; 19 | for(int j = 0; j < num2.size(); j++) { 20 | int dig2 = num2[j] - '0'; 21 | int c = r[i + j] - '0'; 22 | r[i + j] = (dig1 * dig2 + carry + c) % 10 + '0'; 23 | carry = (dig1 * dig2 + carry + c) / 10; 24 | } 25 | 26 | if(carry > 0) { 27 | r[i + num2.size()] = carry + '0'; 28 | } 29 | } 30 | 31 | reverse(r.begin(), r.end()); 32 | r.erase(0, r.find_first_not_of('0')); 33 | return r.empty() ? "0" : r; 34 | } 35 | }; 36 | 37 | int main() { 38 | Solution sln; 39 | cout << sln.multiply("0", "0") << endl; 40 | cout << sln.multiply("123", "2") << endl; 41 | return 0; 42 | } -------------------------------------------------------------------------------- /reverse-words-in-a-string.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | void reverseWords(string &s) { 6 | vector tokens; 7 | tokenize(s, tokens); 8 | 9 | std::reverse(tokens.begin(), tokens.end()); 10 | 11 | s.clear(); 12 | 13 | for(int i = 0; i < (int)tokens.size(); i++) { 14 | s.append(tokens[i]); 15 | if(i != int(tokens.size()) - 1) { 16 | s.append(" "); 17 | } 18 | } 19 | } 20 | 21 | void tokenize(const string& str, vector& tokens, const string& delims = " \t") { 22 | string::size_type lastPos = str.find_first_not_of(delims, 0); 23 | string::size_type pos = str.find_first_of(delims, lastPos); 24 | 25 | while(string::npos != pos || string::npos != lastPos) { 26 | tokens.push_back(str.substr(lastPos, pos - lastPos)); 27 | lastPos = str.find_first_not_of(delims, pos); 28 | pos = str.find_first_of(delims, lastPos); 29 | } 30 | } 31 | }; 32 | 33 | int main() { 34 | Solution sln; 35 | string s = "the sky is blue"; 36 | 37 | cout << s << endl; 38 | 39 | sln.reverseWords(s); 40 | 41 | cout << s << endl; 42 | return 0; 43 | } -------------------------------------------------------------------------------- /binary-tree-level-order-traversal.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | vector > vals; 6 | vector > levelOrder(TreeNode *root) { 7 | build(root, 1); 8 | return vals; 9 | } 10 | 11 | void build(TreeNode* node, int level) { 12 | if(!node) { 13 | return; 14 | } 15 | 16 | if(vals.size() <= level - 1) { 17 | vals.push_back(vector()); 18 | } 19 | 20 | vals[level - 1].push_back(node->val); 21 | 22 | if(node->left) { 23 | build(node->left, level + 1); 24 | } 25 | 26 | if(node->right) { 27 | build(node->right, level + 1); 28 | } 29 | } 30 | }; 31 | 32 | int main() { 33 | TreeNode n1(3); 34 | TreeNode n2(9); 35 | TreeNode n3(20); 36 | TreeNode n4(15); 37 | TreeNode n5(7); 38 | 39 | n1.left = &n2; 40 | n1.right = &n3; 41 | n3.left = &n4; 42 | n3.right = &n5; 43 | 44 | Solution sln; 45 | 46 | auto a = sln.levelOrder(&n1); 47 | for(int i = 0; i < a.size(); i++) { 48 | for(int j = 0; j < a[i].size(); j++) { 49 | cout << a[i][j] << "\t"; 50 | } 51 | cout << endl; 52 | } 53 | return 0; 54 | } -------------------------------------------------------------------------------- /binary-tree-preorder-traversal.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | vector preorderTraversal(TreeNode *root) { 6 | vector vals; 7 | if(root == NULL) { 8 | return vals; 9 | } 10 | 11 | vector nodes; 12 | TreeNode* pre = NULL; 13 | 14 | nodes.push_back(root); 15 | 16 | while(!nodes.empty()) { 17 | TreeNode* n = nodes.back(); 18 | vals.push_back(n->val); 19 | 20 | nodes.pop_back(); 21 | 22 | if(n->right) { 23 | nodes.push_back(n->right); 24 | } 25 | if(n->left) { 26 | nodes.push_back(n->left); 27 | } 28 | } 29 | 30 | return vals; 31 | } 32 | }; 33 | 34 | int main() { 35 | TreeNode n1(1); 36 | 37 | TreeNode n2(2); 38 | n1.right = &n2; 39 | 40 | TreeNode n3(3); 41 | n2.left = &n3; 42 | 43 | Solution sln; 44 | 45 | vector a = sln.preorderTraversal(&n1); 46 | for(int i = 0; i < a.size(); i++) { 47 | cout << a[i]; 48 | if(i != a.size() - 1) { 49 | cout << "\t"; 50 | } else { 51 | cout << endl; 52 | } 53 | } 54 | 55 | return 0; 56 | } -------------------------------------------------------------------------------- /insert-interval.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | static bool comp(Interval a, Interval b) 6 | { 7 | return a.start < b.start; 8 | } 9 | 10 | vector insert(vector &intervals, Interval newInterval) { 11 | auto it = intervals.begin(); 12 | auto it_prev = it; 13 | while(it != intervals.end()) { 14 | if(newInterval.end < it->start) { 15 | if(it != it_prev) { 16 | it = intervals.erase(it_prev, it); 17 | } 18 | intervals.insert(it, newInterval); 19 | return intervals; 20 | } else if(newInterval.start > it->end) { 21 | ++it; 22 | ++it_prev; 23 | continue; 24 | } else { 25 | newInterval.start = min(newInterval.start, it->start); 26 | newInterval.end = max(newInterval.end, it->end); 27 | ++it; 28 | } 29 | } 30 | 31 | if(it != it_prev) { 32 | it = intervals.erase(it_prev, it); 33 | } 34 | intervals.insert(intervals.end(), newInterval); 35 | return intervals; 36 | } 37 | }; 38 | 39 | int main() { 40 | return 0; 41 | } -------------------------------------------------------------------------------- /n-queens.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | vector > vv; 6 | vector > solveNQueens(int n) { 7 | vector pos; 8 | 9 | dfs(pos, 0, n); 10 | 11 | return vv; 12 | } 13 | 14 | void dfs(vector &pos, int k, int n) { 15 | if(n == k) { 16 | int l = pos.size(); 17 | vector v(l, string(l, '.')); 18 | for(int i = 0; i < l; i++) { 19 | v[i][pos[i]] = 'Q'; 20 | } 21 | vv.push_back(v); 22 | return; 23 | } 24 | 25 | for(int i = 0; i < n; i++) { 26 | if(isValid(pos, k, i)) { 27 | pos.push_back(i); 28 | dfs(pos, k + 1, n); 29 | pos.pop_back(); 30 | } 31 | } 32 | } 33 | 34 | bool isValid(vector &pos, int row, int col) { 35 | for(int j = 0; j < pos.size(); j++) { 36 | if(pos[j] == col || abs(j - row) == abs(pos[j] - col)) { 37 | return false; 38 | } 39 | } 40 | return true; 41 | } 42 | }; 43 | 44 | int main() { 45 | Solution sln; 46 | 47 | auto a = sln.solveNQueens(4); 48 | 49 | printVector2(a); 50 | 51 | return 0; 52 | } -------------------------------------------------------------------------------- /subsets-ii.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | vector > res; 6 | 7 | vector > subsetsWithDup(vector &S) { 8 | if(S.empty()) { 9 | return res; 10 | } 11 | 12 | sort(S.begin(), S.end()); 13 | 14 | res.push_back(vector()); 15 | 16 | vector v; 17 | 18 | generate(0, v, S); 19 | 20 | return res; 21 | } 22 | 23 | void generate(int start, vector& v, vector &S) { 24 | if(start == S.size()) { 25 | return; 26 | } 27 | 28 | for(int i = start; i < S.size(); i++) { 29 | v.push_back(S[i]); 30 | 31 | res.push_back(v); 32 | 33 | generate(i + 1, v, S); 34 | 35 | v.pop_back(); 36 | 37 | while(i < S.size() - 1 && S[i] == S[i + 1]) { 38 | i++; 39 | } 40 | } 41 | } 42 | }; 43 | 44 | int main() { 45 | Solution sln; 46 | vector s({1, 2, 2}); 47 | 48 | auto a = sln.subsetsWithDup(s); 49 | 50 | for(int i = 0; i < a.size(); i++) { 51 | for(int j = 0; j < a[i].size(); j++) { 52 | cout << a[i][j] << "\t"; 53 | } 54 | cout << endl; 55 | } 56 | 57 | return 0; 58 | } -------------------------------------------------------------------------------- /permutations-ii.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | vector > vv; 6 | vector visits; 7 | vector > permuteUnique(vector &num) { 8 | if(num.empty()) { 9 | return vv; 10 | } 11 | 12 | visits.resize(num.size(), false); 13 | 14 | sort(num.begin(), num.end()); 15 | 16 | vector v; 17 | dfs(v, num, 0); 18 | 19 | return vv; 20 | } 21 | 22 | void dfs(vector& v, vector& num, int step) { 23 | if(step == num.size()) { 24 | vv.push_back(v); 25 | return; 26 | } 27 | 28 | for(int i = 0; i < num.size(); i++) { 29 | if(!visits[i]) { 30 | if(i > 0 && num[i] == num[i - 1] && visits[i - 1] == 0) { 31 | continue; 32 | } 33 | 34 | visits[i] = true; 35 | 36 | v.push_back(num[i]); 37 | 38 | dfs(v, num, step + 1); 39 | 40 | v.pop_back(); 41 | visits[i] = false; 42 | } 43 | } 44 | } 45 | }; 46 | 47 | int main() { 48 | Solution sln; 49 | 50 | vector num({1, 1, 2}); 51 | auto vv = sln.permuteUnique(num); 52 | 53 | printVector2(vv); 54 | 55 | return 0; 56 | } -------------------------------------------------------------------------------- /search-for-a-range.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | vector searchRange(int A[], int n, int target) { 6 | if(n == 0) { 7 | return vector({-1, -1}); 8 | } 9 | 10 | vector v; 11 | int low = 0; 12 | int high = n - 1; 13 | while(low <= high) { 14 | int mid = (low + high) / 2; 15 | if(A[mid] >= target) { 16 | high = mid - 1; 17 | } else { 18 | low = mid + 1; 19 | } 20 | } 21 | 22 | if(low < n && A[low] == target) { 23 | v.push_back(low); 24 | } else { 25 | return vector({-1, -1}); 26 | } 27 | 28 | low = low; 29 | high = n - 1; 30 | while(low <= high) { 31 | int mid = (low + high) / 2; 32 | if(A[mid] <= target) { 33 | low = mid + 1; 34 | } else { 35 | high = mid - 1; 36 | } 37 | } 38 | 39 | 40 | v.push_back(high); 41 | return v; 42 | } 43 | }; 44 | 45 | int main() { 46 | int a[] = {7, 8, 8}; 47 | int n = sizeof(a) / sizeof(int); 48 | 49 | Solution sln; 50 | auto v = sln.searchRange(a, n, 8); 51 | 52 | printVector(v); 53 | 54 | return 0; 55 | } -------------------------------------------------------------------------------- /binary-tree-level-order-traversal-ii.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | vector > vals; 6 | vector > levelOrderBottom(TreeNode *root) { 7 | build(root, 1); 8 | 9 | reverse(vals.begin(), vals.end()); 10 | 11 | return vals; 12 | } 13 | 14 | void build(TreeNode* node, int level) { 15 | if(!node) { 16 | return; 17 | } 18 | 19 | if(vals.size() <= level - 1) { 20 | vals.push_back(vector()); 21 | } 22 | 23 | vals[level - 1].push_back(node->val); 24 | 25 | if(node->left) { 26 | build(node->left, level + 1); 27 | } 28 | 29 | if(node->right) { 30 | build(node->right, level + 1); 31 | } 32 | } 33 | }; 34 | 35 | int main() { 36 | TreeNode n1(3); 37 | TreeNode n2(9); 38 | TreeNode n3(20); 39 | TreeNode n4(15); 40 | TreeNode n5(7); 41 | 42 | n1.left = &n2; 43 | n1.right = &n3; 44 | n3.left = &n4; 45 | n3.right = &n5; 46 | 47 | Solution sln; 48 | 49 | auto a = sln.levelOrderBottom(&n1); 50 | for(int i = 0; i < a.size(); i++) { 51 | for(int j = 0; j < a[i].size(); j++) { 52 | cout << a[i][j] << "\t"; 53 | } 54 | cout << endl; 55 | } 56 | return 0; 57 | } -------------------------------------------------------------------------------- /unique-paths-ii.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int uniquePathsWithObstacles(vector > &obstacleGrid) { 6 | if(obstacleGrid.empty() || obstacleGrid[0].empty()) { 7 | return 0; 8 | } 9 | 10 | int m = obstacleGrid.size(); 11 | int n = obstacleGrid[0].size(); 12 | 13 | int dp[m][n]; 14 | 15 | dp[0][0] = (obstacleGrid[0][0] == 0 ? 1 : 0); 16 | 17 | for(int i = 1; i < m; i++) { 18 | dp[i][0] = ((dp[i - 1][0] == 1 && obstacleGrid[i][0] == 0) ? 1 : 0); 19 | } 20 | 21 | for(int j = 1; j < n; j++) { 22 | dp[0][j] = ((dp[0][j - 1] == 1 && obstacleGrid[0][j] == 0) ? 1 : 0); 23 | } 24 | 25 | 26 | for(int i = 1; i < m; i++) { 27 | for(int j = 1; j < n; j++) { 28 | if(obstacleGrid[i][j] == 1) { 29 | dp[i][j] = 0; 30 | } else { 31 | dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; 32 | } 33 | } 34 | } 35 | 36 | return dp[m - 1][n - 1]; 37 | } 38 | }; 39 | 40 | int main() { 41 | vector > vv(1, vector(1, 0)); 42 | vv[0][0] = 0; 43 | 44 | Solution sln; 45 | 46 | cout << sln.uniquePathsWithObstacles(vv) << endl; 47 | 48 | return 0; 49 | } -------------------------------------------------------------------------------- /flatten-binary-tree-to-linked-list.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | void flatten(TreeNode *root) { 6 | if(!root) { 7 | return; 8 | } 9 | 10 | vector ns; 11 | TreeNode dummy(0); 12 | 13 | TreeNode* n = &dummy; 14 | 15 | ns.push_back(root); 16 | 17 | while(!ns.empty()) { 18 | TreeNode* p = ns.back(); 19 | ns.pop_back(); 20 | 21 | n->right = p; 22 | n = p; 23 | 24 | 25 | if(p->right) { 26 | ns.push_back(p->right); 27 | p->right = NULL; 28 | } 29 | 30 | if(p->left) { 31 | ns.push_back(p->left); 32 | p->left = NULL; 33 | } 34 | } 35 | } 36 | }; 37 | 38 | int main() { 39 | TreeNode n1(1); 40 | TreeNode n2(2); 41 | TreeNode n3(3); 42 | TreeNode n4(4); 43 | TreeNode n5(5); 44 | TreeNode n6(6); 45 | 46 | n1.left = &n2; 47 | n1.right = &n5; 48 | 49 | n2.left = &n3; 50 | n2.right = &n4; 51 | 52 | n5.right = &n6; 53 | 54 | Solution sln; 55 | 56 | sln.flatten(&n1); 57 | 58 | TreeNode* p = &n1; 59 | while(p) { 60 | cout << p->val << "\t"; 61 | p = p->right; 62 | } 63 | 64 | cout << endl; 65 | return 0; 66 | } -------------------------------------------------------------------------------- /sum-root-to-leaf-numbers.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | vector vals; 6 | int sumNumbers(TreeNode *root) { 7 | if(root == NULL) { 8 | return 0; 9 | } 10 | 11 | vector vs; 12 | string val; 13 | 14 | dfs(vs, root, val); 15 | 16 | int num = 0; 17 | for(int i = 0; i < (int)vals.size(); i++) { 18 | num += atoi(vals[i].c_str()); 19 | } 20 | return num; 21 | } 22 | 23 | void dfs(vector& vs, TreeNode* n, string& str) { 24 | vs.push_back(n); 25 | 26 | str.append(1, '0' + n->val); 27 | 28 | if(!n->left && !n->right) { 29 | vals.push_back(str); 30 | return; 31 | } 32 | 33 | if(n->left) { 34 | dfs(vs, n->left, str); 35 | vs.pop_back(); 36 | str.erase(str.size() - 1); 37 | } 38 | 39 | if(n->right) { 40 | dfs(vs, n->right, str); 41 | vs.pop_back(); 42 | str.erase(str.size() - 1); 43 | } 44 | } 45 | }; 46 | 47 | int main() { 48 | TreeNode n1(1); 49 | TreeNode n2(2); 50 | TreeNode n3(3); 51 | n1.left = &n2; 52 | n1.right = &n3; 53 | 54 | Solution sln; 55 | 56 | cout << sln.sumNumbers(&n1) << endl; 57 | 58 | return 0; 59 | } -------------------------------------------------------------------------------- /median-of-two-sorted-arrays.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | double findKth(int a[], int m, int b[], int n, int k) { 6 | if(m > n) { 7 | return findKth(b, n, a, m, k); 8 | } 9 | if(m == 0) { 10 | return b[k - 1]; 11 | } 12 | if(k == 1) { 13 | return min(a[0], b[0]); 14 | } 15 | 16 | int pa = min(k / 2, m); 17 | int pb = k - pa; 18 | if(a[pa - 1] < b[pb - 1]) { 19 | return findKth(a + pa, m - pa, b, n, k - pa); 20 | } else if(a[pa - 1] > b[pb - 1]) { 21 | return findKth(a, m, b + pb, n - pb, k - pb); 22 | } else { 23 | return a[pa - 1]; 24 | } 25 | } 26 | 27 | double findMedianSortedArrays(int A[], int m, int B[], int n) { 28 | int t = m + n; 29 | if(t & 0x01) { 30 | return findKth(A, m, B, n, t / 2 + 1); 31 | } else { 32 | return (findKth(A, m, B, n, t / 2) 33 | + findKth(A, m, B, n, t / 2 + 1)) / 2; 34 | } 35 | } 36 | }; 37 | 38 | int main() { 39 | Solution sln; 40 | 41 | int a[] = {}; 42 | int m = sizeof(a) / sizeof(int); 43 | int b[] = {1}; 44 | int n = sizeof(b) / sizeof(int); 45 | 46 | cout << sln.findMedianSortedArrays(a, m, b, n) << endl; 47 | return 0; 48 | } 49 | 50 | -------------------------------------------------------------------------------- /valid-palindrome.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | bool getChar(char c, char* p) { 6 | if(c >= 'a' && c <= 'z') { 7 | *p = c; 8 | return true; 9 | } else if (c >= 'A' && c <= 'Z') { 10 | c += 32; 11 | *p = c; 12 | return true; 13 | } else if (c >= '0' && c <= '9') { 14 | *p = c; 15 | return true; 16 | } else { 17 | return false; 18 | } 19 | } 20 | 21 | bool isPalindrome(string s) { 22 | if(s.empty()) { 23 | return true; 24 | } 25 | 26 | string dst; 27 | dst.reserve(s.size()); 28 | 29 | for(int i = 0; i < (int)s.size();i++) { 30 | char b; 31 | if(getChar(s[i], &b)) { 32 | dst.append(1, b); 33 | } 34 | } 35 | 36 | int i = 0; 37 | int j = (int)dst.size() - 1; 38 | 39 | 40 | while(i < j) { 41 | if(dst[i] != dst[j]) { 42 | return false; 43 | } 44 | i++; 45 | j--; 46 | } 47 | return true; 48 | } 49 | }; 50 | 51 | int main() { 52 | Solution sln; 53 | 54 | cout << sln.isPalindrome("A man, a plan, a canal: Panama") << endl; 55 | cout << sln.isPalindrome("race a car") << endl; 56 | 57 | return 0; 58 | } -------------------------------------------------------------------------------- /simplify-path.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | string simplifyPath(string path) { 6 | if(path.empty()) { 7 | return path; 8 | } 9 | 10 | vector v; 11 | 12 | size_t pos = 0; 13 | size_t pos1 = 0; 14 | 15 | while(true) { 16 | pos = path.find_first_not_of('/', pos); 17 | if(pos == string::npos) { 18 | break; 19 | } 20 | 21 | pos1 = path.find_first_of('/', pos); 22 | 23 | string sub = path.substr(pos, pos1 - pos); 24 | pos = pos1; 25 | 26 | if(sub == ".") { 27 | continue; 28 | } else if(sub == "..") { 29 | if(!v.empty()) { 30 | v.pop_back(); 31 | continue; 32 | } 33 | } else { 34 | v.push_back(sub); 35 | } 36 | } 37 | 38 | string s; 39 | string sep = "/"; 40 | for(int i = 0; i < v.size(); i++) { 41 | s.append(sep); 42 | s.append(v[i]); 43 | } 44 | 45 | if(s.empty()) { 46 | return "/"; 47 | } 48 | 49 | return s; 50 | } 51 | }; 52 | 53 | int main() { 54 | Solution sln; 55 | 56 | cout << sln.simplifyPath("/a/./b/../../c/") << endl; 57 | 58 | return 0; 59 | } -------------------------------------------------------------------------------- /remove-duplicates-from-sorted-list-ii.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | ListNode *deleteDuplicates(ListNode *head) { 6 | if(!head) { 7 | return head; 8 | } 9 | 10 | ListNode dummy(0); 11 | dummy.next = head; 12 | ListNode* prev = &dummy; 13 | ListNode* p = head; 14 | while(p && p->next) { 15 | if(p->val != p->next->val) { 16 | prev = p; 17 | p = p->next; 18 | } else { 19 | int val = p->val; 20 | ListNode* n = p->next->next; 21 | while(n) { 22 | if(n->val != val) { 23 | break; 24 | } 25 | n = n->next; 26 | } 27 | 28 | prev->next = n; 29 | p = n; 30 | } 31 | } 32 | return dummy.next; 33 | } 34 | }; 35 | 36 | 37 | 38 | int main() { 39 | Solution sln; 40 | ListNode* n1 = createListNode(vector({1, 2, 3, 3, 4, 4, 5})); 41 | n1 = sln.deleteDuplicates(n1); 42 | printListNode(n1); 43 | 44 | n1 = createListNode(vector({1, 1, 1, 2, 3})); 45 | n1 = sln.deleteDuplicates(n1); 46 | printListNode(n1); 47 | 48 | n1 = createListNode(vector({1, 1, 1})); 49 | n1 = sln.deleteDuplicates(n1); 50 | printListNode(n1); 51 | return 0; 52 | } -------------------------------------------------------------------------------- /reverse-nodes-in-k-group.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | ListNode *reverseKGroup(ListNode *head, int k) { 6 | if(k <= 1 || !head) { 7 | return head; 8 | } 9 | 10 | ListNode dummy(0); 11 | dummy.next = head; 12 | ListNode* p = &dummy; 13 | ListNode* prev = &dummy; 14 | 15 | while(p) { 16 | prev = p; 17 | for(int i = 0; i < k; i++){ 18 | p = p->next; 19 | if(!p) { 20 | return dummy.next; 21 | } 22 | } 23 | 24 | p = reverse(prev, p->next); 25 | } 26 | 27 | return dummy.next; 28 | } 29 | 30 | ListNode* reverse(ListNode* prev, ListNode* end) { 31 | ListNode* p = prev->next; 32 | 33 | while(p->next != end) { 34 | ListNode* n = p->next; 35 | p->next = n->next; 36 | n->next = prev->next; 37 | prev->next = n; 38 | } 39 | 40 | return p; 41 | } 42 | }; 43 | 44 | int main() { 45 | Solution sln; 46 | 47 | ListNode* n = createListNode(vector({1, 2, 3, 4, 5})); 48 | 49 | n = sln.reverseKGroup(n, 5); 50 | 51 | printListNode(n); 52 | 53 | n = createListNode(vector({1, 2, 3, 4})); 54 | 55 | n = sln.reverseKGroup(n, 2); 56 | 57 | printListNode(n); 58 | 59 | return 0; 60 | } -------------------------------------------------------------------------------- /3sum-closest.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int threeSumClosest(vector &num, int target) { 6 | sort(num.begin(), num.end()); 7 | int minV = numeric_limits::max(); 8 | 9 | int minS = 0; 10 | int len = num.size(); 11 | 12 | for(int i = 0; i < len; i++) { 13 | int start = i + 1; 14 | int end = len - 1; 15 | while(start < end) { 16 | int sum = num[i] + num[start] + num[end]; 17 | if(sum == target) { 18 | return target; 19 | } else if(sum < target) { 20 | if(target - sum < minV) { 21 | minV = target - sum; 22 | minS = sum; 23 | } 24 | start++; 25 | } else { 26 | if(sum - target < minV) { 27 | minV = sum - target; 28 | minS = sum; 29 | } 30 | end--; 31 | } 32 | } 33 | while(i < len - 1 && num[i + 1] == num[i]) { 34 | i++; 35 | } 36 | } 37 | 38 | return minS; 39 | } 40 | }; 41 | 42 | int main() { 43 | Solution sln; 44 | 45 | vector nums({0, 0, 0}); 46 | 47 | cout << sln.threeSumClosest(nums, 1) << endl; 48 | 49 | return 0; 50 | } -------------------------------------------------------------------------------- /best-time-to-buy-and-sell-stock-iii.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int maxProfit(vector &prices) { 6 | int len = (int)prices.size(); 7 | if(len <= 1) { 8 | return 0; 9 | } 10 | 11 | vector profits; 12 | profits.resize(len); 13 | 14 | int minP = prices[0]; 15 | int sum = numeric_limits::min(); 16 | for(int i = 1; i < len; i++) { 17 | minP = min(minP, prices[i - 1]); 18 | profits[i] = max(sum, prices[i] - minP); 19 | 20 | sum = profits[i]; 21 | } 22 | 23 | int maxP = prices[len - 1]; 24 | int sum2 = numeric_limits::min(); 25 | 26 | for(int i = len - 2; i >= 0; i--) { 27 | maxP = max(maxP, prices[i + 1]); 28 | sum2 = max(sum2, maxP - prices[i]); 29 | 30 | if(sum2 > 0) { 31 | profits[i] = profits[i] + sum2; 32 | sum = max(sum, profits[i]); 33 | } 34 | } 35 | 36 | 37 | return sum > 0 ? sum : 0; 38 | } 39 | }; 40 | 41 | int main() { 42 | Solution sln; 43 | vector prices({1, 2}); 44 | 45 | cout << sln.maxProfit(prices) << endl; 46 | 47 | prices = {2,1,2,0,1}; 48 | 49 | cout << sln.maxProfit(prices) << endl; 50 | 51 | prices = {3,2,6,5,0,3}; 52 | 53 | cout << sln.maxProfit(prices) << endl; 54 | 55 | return 0; 56 | } -------------------------------------------------------------------------------- /spiral-matrix.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | vector spiralOrder(vector > &matrix) { 6 | vector v; 7 | if(matrix.empty() || matrix[0].empty()) { 8 | return v; 9 | } 10 | int m = matrix.size(); 11 | int n = matrix[0].size(); 12 | int cycle = (min(m, n) + 1) / 2; 13 | 14 | int a = n; 15 | int b = m; 16 | 17 | for(int i = 0; i < cycle; i++, a -= 2, b -= 2) { 18 | for(int c = i; c < i + a; c++) { 19 | v.push_back(matrix[i][c]); 20 | } 21 | 22 | for(int r = i + 1; r < i + b; r++) { 23 | v.push_back(matrix[r][i + a - 1]); 24 | } 25 | 26 | if(a == 1 || b == 1) { 27 | break; 28 | } 29 | 30 | for(int c = i + a - 2; c >= i; c--) { 31 | v.push_back(matrix[i + b - 1][c]); 32 | } 33 | 34 | for(int r = i + b - 2; r > i; r--) { 35 | v.push_back(matrix[r][i]); 36 | } 37 | } 38 | 39 | return v; 40 | } 41 | }; 42 | 43 | int main() { 44 | Solution sln; 45 | 46 | vector > matrix(3, vector(3, 0)); 47 | for(int i = 0; i < 9; i++) { 48 | matrix[i / 3][i % 3] = i + 1; 49 | } 50 | 51 | auto a = sln.spiralOrder(matrix); 52 | 53 | printVector(a); 54 | 55 | return 0; 56 | } -------------------------------------------------------------------------------- /search-a-2d-matrix.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | bool searchMatrix(vector > &matrix, int target) { 6 | if(matrix.empty() || matrix[0].empty()) { 7 | return false; 8 | } 9 | int row = matrix.size(); 10 | int col = matrix[0].size(); 11 | 12 | if(matrix[0][0] > target) { 13 | return false; 14 | } 15 | 16 | int low = 0; 17 | int high = row - 1; 18 | int mid = row / 2; 19 | while(low < high) { 20 | if(matrix[mid][0] <= target) { 21 | low = mid; 22 | } else { 23 | high = mid - 1; 24 | } 25 | 26 | mid = (low + high + 1) / 2; 27 | } 28 | 29 | vector& m = matrix[mid]; 30 | 31 | low = 0; 32 | high = matrix[mid].size() - 1; 33 | while(low <= high) { 34 | mid = (low + high) / 2; 35 | if(m[mid] == target) { 36 | return true; 37 | } else if(m[mid] < target) { 38 | low = mid + 1; 39 | } else { 40 | high = mid - 1; 41 | } 42 | } 43 | 44 | return false; 45 | } 46 | }; 47 | 48 | int main() { 49 | vector > a; 50 | a.resize(1); 51 | a[0] = vector({1, 3}); 52 | 53 | Solution sln; 54 | 55 | cout << sln.searchMatrix(a, 3) << endl; 56 | 57 | return 0; 58 | } -------------------------------------------------------------------------------- /substring-with-concatenation-of-all-words.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | vector findSubstring(string S, vector &L) { 6 | vector v; 7 | if(S.empty() || L.empty()) { 8 | return v; 9 | } 10 | 11 | int len = L[0].size(); 12 | 13 | unordered_map m; 14 | for(int i = 0; i < L.size(); i++) { 15 | m[L[i]]++; 16 | } 17 | 18 | int slen = S.size() - L.size() * len; 19 | 20 | for(int i = 0; i <= slen; i++) { 21 | unordered_map mm(m); 22 | for(int j = i; j < S.size(); j+=len) { 23 | string s = S.substr(j, len); 24 | auto it = mm.find(s); 25 | if(it == mm.end()) { 26 | break; 27 | } else { 28 | it->second--; 29 | if(it->second == 0) { 30 | mm.erase(it); 31 | } 32 | if(mm.empty()) { 33 | v.push_back(i); 34 | break; 35 | } 36 | } 37 | } 38 | } 39 | 40 | return v; 41 | } 42 | }; 43 | 44 | int main() { 45 | Solution sln; 46 | 47 | vector s({"foo", "bar"}); 48 | 49 | auto v = sln.findSubstring("barfoothefoobarman", s); 50 | 51 | printVector(v); 52 | 53 | return 0; 54 | } -------------------------------------------------------------------------------- /add-two-numbers.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { 6 | ListNode dummy(0); 7 | ListNode* p = &dummy; 8 | 9 | int cn = 0; 10 | 11 | while(l1 && l2) { 12 | int val = cn + l1->val + l2->val; 13 | cn = val / 10; 14 | val = val % 10; 15 | p->next = new ListNode(val); 16 | p = p->next; 17 | l1 = l1->next; 18 | l2 = l2->next; 19 | } 20 | 21 | while(l1) { 22 | int val = cn + l1->val; 23 | cn = val / 10; 24 | val = val % 10; 25 | p->next = new ListNode(val); 26 | p = p->next; 27 | l1 = l1->next; 28 | } 29 | 30 | while(l2) { 31 | int val = cn + l2->val; 32 | cn = val / 10; 33 | val = val % 10; 34 | p->next = new ListNode(val); 35 | p = p->next; 36 | l2 = l2->next; 37 | } 38 | 39 | if(cn != 0) { 40 | p->next = new ListNode(cn); 41 | p = p->next; 42 | } 43 | 44 | return dummy.next; 45 | } 46 | }; 47 | 48 | int main() { 49 | Solution sln; 50 | 51 | ListNode* n1 = createListNode(vector({1, 8})); 52 | ListNode* n2 = createListNode(vector({0})); 53 | 54 | ListNode* n = sln.addTwoNumbers(n1, n2); 55 | printListNode(n); 56 | return 0; 57 | } -------------------------------------------------------------------------------- /palindrome-partitioning.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | vector > vvs; 6 | 7 | vector > partition(string s) { 8 | vector vs; 9 | split(s, 0, vs); 10 | return vvs; 11 | } 12 | 13 | void split(const string&s, size_t start, vector& vs) { 14 | if(start == s.size()) { 15 | vvs.push_back(vs); 16 | return; 17 | } 18 | 19 | for(size_t i = start; i < s.size(); i++) { 20 | if(isPalindrome(s, start, i)) { 21 | vs.push_back(s.substr(start, i - start + 1)); 22 | split(s, i + 1, vs); 23 | vs.pop_back(); 24 | } 25 | } 26 | } 27 | 28 | 29 | bool isPalindrome(const string& s, size_t start, size_t end) { 30 | if(start == end) { 31 | return true; 32 | } 33 | 34 | while(start < end) { 35 | if(s[start] != s[end]) { 36 | return false; 37 | } 38 | start++; 39 | end--; 40 | } 41 | 42 | return true; 43 | } 44 | }; 45 | 46 | int main() { 47 | Solution sln; 48 | 49 | vector > vvs = sln.partition("aab"); 50 | for(size_t i = 0; i < vvs.size(); i++) { 51 | for(size_t j = 0; j < vvs[i].size(); j++) { 52 | cout << vvs[i][j] << "\t"; 53 | } 54 | cout << endl; 55 | } 56 | 57 | return 0; 58 | } -------------------------------------------------------------------------------- /integer-to-roman.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | string intToRoman(int num) { 6 | string s; 7 | 8 | char symbol[] = {'I', 'V', 'X', 'L', 'C', 'D', 'M'}; 9 | 10 | int scale = 1000; 11 | 12 | for(int i = 6; i >= 0; i -= 2) { 13 | int d = num / scale; 14 | if(d != 0) { 15 | switch(d) { 16 | case 1: 17 | case 2: 18 | case 3: 19 | s.append(d, symbol[i]); 20 | break; 21 | case 4: 22 | s.append(1, symbol[i]); 23 | s.append(1, symbol[i + 1]); 24 | break; 25 | case 5: 26 | s.append(1, symbol[i + 1]); 27 | break; 28 | case 6: 29 | case 7: 30 | case 8: 31 | s.append(1, symbol[i + 1]); 32 | s.append(d - 5, symbol[i]); 33 | break; 34 | case 9: 35 | s.append(1, symbol[i]); 36 | s.append(1, symbol[i + 2]); 37 | break; 38 | } 39 | } 40 | 41 | num %= scale; 42 | scale /= 10; 43 | } 44 | 45 | return s; 46 | } 47 | }; 48 | 49 | int main() { 50 | return 0; 51 | } -------------------------------------------------------------------------------- /lru-cache.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class LRUCache{ 4 | public: 5 | typedef pair KVPair_t; 6 | typedef list ListKV_t; 7 | typedef map MapCache_t; 8 | 9 | LRUCache(int capacity) { 10 | maxSize = capacity; 11 | } 12 | 13 | int get(int key) { 14 | MapCache_t::iterator it = caches.find(key); 15 | if (it != caches.end()) 16 | { 17 | kvs.splice(kvs.begin(), kvs, it->second); 18 | return it->second->second; 19 | } 20 | return -1; 21 | } 22 | 23 | void set(int key, int value) { 24 | MapCache_t::iterator it = caches.find(key); 25 | if(it == caches.end()) { 26 | if(int(kvs.size()) == maxSize) { 27 | int k = kvs.back().first; 28 | caches.erase(k); 29 | kvs.pop_back(); 30 | } 31 | 32 | kvs.push_front(KVPair_t(key, value)); 33 | caches[key] = kvs.begin(); 34 | } else { 35 | caches[key]->second = value; 36 | kvs.splice(kvs.begin(), kvs, it->second); 37 | } 38 | } 39 | 40 | private: 41 | int maxSize; 42 | MapCache_t caches; 43 | ListKV_t kvs; 44 | }; 45 | 46 | int main() { 47 | LRUCache c(2); 48 | c.set(2,1); 49 | c.set(1,1); 50 | cout << c.get(2) << endl; 51 | c.set(4,1); 52 | 53 | cout << c.get(1) << endl; 54 | cout << c.get(2) << endl; 55 | 56 | return 0; 57 | } -------------------------------------------------------------------------------- /3sum.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | vector > threeSum(vector &num) { 6 | vector > vv; 7 | int start, end, i; 8 | 9 | sort(num.begin(), num.end()); 10 | 11 | for(int i = 0; i < num.size(); i++) { 12 | int target = 0 - num[i]; 13 | int start = i + 1; 14 | int end = num.size() - 1; 15 | 16 | while(start < end) { 17 | if(num[start] + num[end] == target) { 18 | vv.push_back(vector({num[i], num[start], num[end]})); 19 | start++; 20 | end--; 21 | 22 | while(start < end && num[start] == num[start - 1]) { 23 | start++; 24 | } 25 | 26 | while(start < end && num[end + 1] == num[end]) { 27 | end--; 28 | } 29 | } else if(num[start] + num[end] < target) { 30 | start++; 31 | } else { 32 | end--; 33 | } 34 | } 35 | 36 | while(i < num.size() - 1 && num[i + 1] == num[i]) { 37 | i++; 38 | } 39 | } 40 | 41 | return vv; 42 | } 43 | }; 44 | 45 | int main() { 46 | Solution sln; 47 | 48 | vector nums({-1, 0, 1, 2, -1, -4}); 49 | auto vv = sln.threeSum(nums); 50 | 51 | printVector2(vv); 52 | 53 | return 0; 54 | } -------------------------------------------------------------------------------- /binary-tree-postorder-traversal.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | vector postorderTraversal(TreeNode *root) { 6 | vector vals; 7 | if(root == NULL) { 8 | return vals; 9 | } 10 | 11 | vector nodes; 12 | TreeNode* pre = NULL; 13 | 14 | nodes.push_back(root); 15 | 16 | while(!nodes.empty()) { 17 | TreeNode* p = nodes.back(); 18 | if((p->left == NULL && p->right == NULL) || 19 | (pre != NULL && (pre == p->left || pre == p->right))) { 20 | vals.push_back(p->val); 21 | nodes.pop_back(); 22 | pre = p; 23 | } else { 24 | if(p->right != NULL) { 25 | nodes.push_back(p->right); 26 | } 27 | 28 | if(p->left != NULL) { 29 | nodes.push_back(p->left); 30 | } 31 | } 32 | } 33 | 34 | return vals; 35 | } 36 | }; 37 | 38 | int main() { 39 | TreeNode n1(1); 40 | 41 | TreeNode n2(2); 42 | n1.right = &n2; 43 | 44 | TreeNode n3(3); 45 | n2.left = &n3; 46 | 47 | Solution sln; 48 | 49 | vector a = sln.postorderTraversal(&n1); 50 | for(int i = 0; i < a.size(); i++) { 51 | cout << a[i]; 52 | if(i != a.size() - 1) { 53 | cout << "\t"; 54 | } else { 55 | cout << endl; 56 | } 57 | } 58 | 59 | return 0; 60 | } -------------------------------------------------------------------------------- /minimum-window-substring.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | string minWindow(string S, string T) { 6 | if(S.empty() || S.size() < T.size()) { 7 | return ""; 8 | } 9 | 10 | vector appearCnt(256, 0); 11 | vector expectCnt(256, 0); 12 | for(int i = 0; i < T.size(); i++) { 13 | expectCnt[T[i]]++; 14 | } 15 | 16 | int minV = INT_MAX; 17 | int start = 0; 18 | int end = 0; 19 | int cnt = 0; 20 | 21 | for(int i = 0; i < S.size(); i++) { 22 | char c = S[i]; 23 | if(expectCnt[c] > 0) { 24 | appearCnt[c]++; 25 | if(appearCnt[c] <= expectCnt[c]) { 26 | cnt++; 27 | } 28 | } 29 | 30 | if(cnt == T.size()) { 31 | while(appearCnt[S[end]] > expectCnt[S[end]] || 32 | expectCnt[S[end]] == 0) { 33 | appearCnt[S[end]]--; 34 | end++; 35 | } 36 | 37 | if(minV > (i - end + 1)) { 38 | minV = i - end + 1; 39 | start = end; 40 | } 41 | } 42 | } 43 | 44 | if(minV == INT_MAX) { 45 | return ""; 46 | } 47 | 48 | return S.substr(start, minV); 49 | } 50 | }; 51 | 52 | int main() { 53 | Solution sln; 54 | 55 | cout << sln.minWindow("ADOBECODEBANC", "ABC") << endl; 56 | 57 | return 0; 58 | } -------------------------------------------------------------------------------- /letter-combinations-of-a-phone-number.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | vector letters; 6 | vector vv; 7 | 8 | vector letterCombinations(string digits) { 9 | if(digits.empty()) { 10 | return vv; 11 | } 12 | 13 | letters.resize(10); 14 | letters[0] = ' '; 15 | letters[1] = ""; 16 | letters[2] = "abc"; 17 | letters[3] = "def"; 18 | letters[4] = "ghi"; 19 | letters[5] = "jkl"; 20 | letters[6] = "mno"; 21 | letters[7] = "pqrs"; 22 | letters[8] = "tuv"; 23 | letters[9] = "wxyz"; 24 | 25 | 26 | for(int i = 0; i < digits.size(); i++) { 27 | vv = merge(vv, digits[i]); 28 | } 29 | 30 | return vv; 31 | } 32 | 33 | vector merge(const vector& v, char digit) { 34 | string s = letters[digit - '0']; 35 | vector vv; 36 | if(v.empty()) { 37 | for(int i = 0; i < s.size(); i++) { 38 | vv.push_back(string(1, s[i])); 39 | } 40 | } else { 41 | for(int i = 0; i < v.size(); i++) { 42 | for(int j = 0; j < s.size(); j++) { 43 | vv.push_back(v[i] + s[j]); 44 | } 45 | } 46 | } 47 | return vv; 48 | } 49 | }; 50 | 51 | int main() { 52 | Solution sln; 53 | 54 | auto v = sln.letterCombinations("23"); 55 | printVector(v); 56 | 57 | return 0; 58 | } -------------------------------------------------------------------------------- /maximal-rectangle.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int maximalRectangle(vector > &matrix) { 6 | if(matrix.empty() || matrix[0].empty()) { 7 | return 0; 8 | } 9 | 10 | int m = matrix.size(); 11 | int n = matrix[0].size(); 12 | 13 | vector > height(m, vector(n, 0)); 14 | for(int i = 0; i < m; i++) { 15 | for(int j = 0; j < n; j++) { 16 | if(matrix[i][j] == '0') { 17 | height[i][j] = 0; 18 | } else { 19 | height[i][j] = (i == 0) ? 1 : height[i - 1][j] + 1; 20 | } 21 | } 22 | } 23 | 24 | int maxArea = 0; 25 | for(int i = 0; i < m; i++) { 26 | maxArea = max(maxArea, largestRectangleArea(height[i])); 27 | } 28 | return maxArea; 29 | } 30 | 31 | int largestRectangleArea(vector &height) { 32 | vector s; 33 | height.push_back(0); 34 | 35 | int sum = 0; 36 | int i = 0; 37 | while(i < height.size()) { 38 | if(s.empty() || height[i] > height[s.back()]) { 39 | s.push_back(i); 40 | i++; 41 | } else { 42 | int t = s.back(); 43 | s.pop_back(); 44 | sum = max(sum, height[t] * (s.empty() ? i : i - s.back() - 1)); 45 | } 46 | } 47 | 48 | return sum; 49 | } 50 | }; 51 | 52 | int main() { 53 | return 0; 54 | } -------------------------------------------------------------------------------- /reorder-list.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | void reorderList(ListNode *head) { 6 | if(head == NULL || head->next == NULL) { 7 | return; 8 | } 9 | 10 | ListNode* fast = head; 11 | ListNode* slow = head; 12 | 13 | while(fast->next != NULL && fast->next->next != NULL) { 14 | fast = fast->next->next; 15 | slow = slow->next; 16 | } 17 | 18 | fast = slow->next; 19 | slow->next = NULL; 20 | 21 | 22 | ListNode dummy(0); 23 | while(fast) { 24 | ListNode* n = dummy.next; 25 | dummy.next = fast; 26 | ListNode* nn = fast->next; 27 | fast->next = n; 28 | fast = nn; 29 | } 30 | 31 | slow = head; 32 | fast = dummy.next; 33 | 34 | while(slow) { 35 | if(fast != NULL) { 36 | ListNode* n = slow->next; 37 | slow->next = fast; 38 | ListNode* nn = fast->next; 39 | fast->next = n; 40 | fast = nn; 41 | slow = n; 42 | } else { 43 | break; 44 | } 45 | } 46 | } 47 | }; 48 | 49 | int main() { 50 | ListNode n1(1); 51 | ListNode n2(2); 52 | ListNode n3(3); 53 | ListNode n4(4); 54 | 55 | n1.next = &n2; 56 | n2.next = &n3; 57 | n3.next = &n4; 58 | 59 | Solution sln; 60 | 61 | sln.reorderList(&n1); 62 | 63 | printListNode(&n1); 64 | 65 | return 0; 66 | } -------------------------------------------------------------------------------- /wildcard-matching.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | bool isMatch(const char *s, const char *p) { 6 | const char* star = NULL; 7 | const char *ss = s; 8 | while(*s) { 9 | if(*p == '?' || *p == *s) { 10 | s++; 11 | p++; 12 | continue; 13 | } 14 | if(*p == '*') { 15 | star = p++; 16 | ss = s; 17 | continue; 18 | } 19 | if(star) { 20 | p = star + 1; 21 | s = ++ss; 22 | continue; 23 | } 24 | return false; 25 | } 26 | 27 | while(*p == '*') { 28 | p++; 29 | } 30 | return !*p; 31 | } 32 | }; 33 | 34 | int main() { 35 | Solution sln; 36 | 37 | // cout << sln.isMatch("aa", "a") << endl; 38 | // cout << sln.isMatch("aa", "aa") << endl; 39 | // cout << sln.isMatch("aaa", "aa") << endl; 40 | // cout << sln.isMatch("aa", "*") << endl; 41 | // cout << sln.isMatch("aa", "a*") << endl; 42 | // cout << sln.isMatch("ab", "?*") << endl; 43 | // cout << sln.isMatch("aab", "c*a*b") << endl; 44 | // cout << sln.isMatch("", "*") << endl; 45 | // cout << sln.isMatch("c", "*?*") << endl; 46 | // cout << sln.isMatch("c", "**?*") << endl; 47 | // cout << sln.isMatch("", "") << endl; 48 | cout << sln.isMatch("b", "*?*?*") << endl; 49 | cout << sln.isMatch("hi", "*?") << endl; 50 | 51 | return 0; 52 | } -------------------------------------------------------------------------------- /copy-list-with-random-pointer.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | RandomListNode *copyRandomList(RandomListNode *head) { 6 | if(head == NULL) { 7 | return NULL; 8 | } 9 | 10 | RandomListNode* n = NULL; 11 | RandomListNode* h = head; 12 | while(h) { 13 | RandomListNode* node = new RandomListNode(h->label); 14 | node->random = h->random; 15 | 16 | n = h->next; 17 | 18 | h->next = node; 19 | node->next = n; 20 | h = n; 21 | } 22 | h = head->next; 23 | while(h) { 24 | if(h->random != NULL) { 25 | h->random = h->random->next; 26 | } 27 | if(!h->next) { 28 | break; 29 | } 30 | h = h->next->next; 31 | } 32 | 33 | h = head; 34 | RandomListNode dummy(0); 35 | RandomListNode* p = &dummy; 36 | while(h) { 37 | n = h->next; 38 | p->next = n; 39 | p = n; 40 | RandomListNode* nn = n->next; 41 | h->next = n->next; 42 | h = n->next; 43 | } 44 | 45 | return dummy.next; 46 | } 47 | }; 48 | 49 | int main() { 50 | RandomListNode n1(-1); 51 | Solution sln; 52 | RandomListNode* n2 = sln.copyRandomList(&n1); 53 | 54 | RandomListNode* h = n2; 55 | while(h) { 56 | cout << h->label << "\t" << h->random << endl; 57 | h = h->next; 58 | } 59 | 60 | return 0; 61 | } -------------------------------------------------------------------------------- /find-minimum-in-rotated-sorted-array-ii.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int findMin(vector &num) { 6 | int size = num.size(); 7 | 8 | if(size == 0) { 9 | return 0; 10 | } else if(size == 1) { 11 | return num[0]; 12 | } else if(size == 2) { 13 | return min(num[0], num[1]); 14 | } 15 | 16 | int start = 0; 17 | int stop = size - 1; 18 | 19 | while(start < stop - 1) { 20 | if(num[start] < num[stop]) { 21 | return num[start]; 22 | } 23 | 24 | int mid = start + (stop - start) / 2; 25 | if(num[mid] > num[start]) { 26 | start = mid; 27 | } else if(num[mid] < num[start]) { 28 | stop = mid; 29 | } else if(num[mid] < num[stop]){ 30 | stop = mid; 31 | } else if(num[mid] > num[stop]){ 32 | start++; 33 | } else{ 34 | start++; 35 | stop--; 36 | } 37 | } 38 | 39 | return min(num[start], num[stop]); 40 | } 41 | }; 42 | 43 | int main() { 44 | Solution sln; 45 | 46 | vector num{1,1}; 47 | 48 | cout << sln.findMin(num) << endl; 49 | 50 | num = vector{3,3,1,3}; 51 | cout << sln.findMin(num) << endl; 52 | 53 | num = vector{3,1,3}; 54 | cout << sln.findMin(num) << endl; 55 | 56 | num = vector{3,5,1}; 57 | cout << sln.findMin(num) << endl; 58 | 59 | return 0; 60 | } 61 | -------------------------------------------------------------------------------- /sudoku-solver.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | void solveSudoku(vector > &board) { 6 | dfs(board); 7 | } 8 | 9 | bool dfs(vector > &board) { 10 | for(int i = 0; i < 9; i++) { 11 | for(int j = 0; j < 9; j++) { 12 | if(board[i][j] == '.') { 13 | for(int k = 0; k < 9; k++) { 14 | board[i][j] = k + 1 + '0'; 15 | if(isValid(board, i, j) && dfs(board)) { 16 | return true; 17 | } 18 | board[i][j] = '.'; 19 | } 20 | return false; 21 | } 22 | } 23 | } 24 | return true; 25 | } 26 | 27 | bool isValid(vector >& board, int x, int y) { 28 | char c = board[x][y]; 29 | for(int i = 0; i < 9; i++) { 30 | if(i != x && board[i][y] == c) { 31 | return false; 32 | } 33 | if(i != y && board[x][i] == c) { 34 | return false; 35 | } 36 | } 37 | 38 | int xx = x / 3 * 3; 39 | int yy = y / 3 * 3; 40 | for(int i = xx; i < xx + 3; i++) { 41 | for(int j = yy; j < yy + 3; j++) { 42 | if(i != x && j != y && board[i][j] == c) { 43 | return false; 44 | } 45 | } 46 | } 47 | 48 | return true; 49 | } 50 | 51 | }; 52 | 53 | int main() { 54 | return 0; 55 | } -------------------------------------------------------------------------------- /valid-number.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | bool isNumber(const char* s) 6 | { 7 | int state = 0; 8 | while(*s) { 9 | state = getNextState(state, *s); 10 | if(state == -1) { 11 | return false; 12 | } 13 | s++; 14 | } 15 | 16 | state = getNextState(state, ' '); 17 | return state == 8; 18 | } 19 | 20 | int getNextState(int state, char c) 21 | { 22 | int transitionTable[][6] = { {0,2,1,3,-1,-1}, 23 | {-1,2,-1,3,-1,-1}, 24 | {8,2,-1,4,5,-1}, 25 | {-1,4,-1,-1,-1,-1}, 26 | {8,4,-1,-1,5,-1}, 27 | {-1,7,6,-1,-1,-1}, 28 | {-1,7,-1,-1,-1,-1}, 29 | {8,7,-1,-1,-1,-1}, 30 | {8,-1,-1,-1,-1,-1} 31 | }; 32 | return transitionTable[state][getSymbol(c)]; 33 | } 34 | 35 | int getSymbol(char c) 36 | { 37 | switch(c) 38 | { 39 | case ' ': case '\t': return 0; 40 | case '0': case '1': case '2':case '3': case '4': case '5': case '6': case '7': case '8': case '9': return 1; 41 | case '+': case '-': return 2; 42 | case '.': return 3; 43 | case 'E': case 'e': return 4; 44 | default: return 5; 45 | } 46 | } 47 | }; 48 | 49 | int main() { 50 | return 0; 51 | } -------------------------------------------------------------------------------- /populating-next-right-pointers-in-each-node.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | void connect(TreeLinkNode *root) { 6 | if(!root) { 7 | return; 8 | } 9 | 10 | TreeLinkNode* p = root; 11 | TreeLinkNode* left = NULL; 12 | while(p) { 13 | if(!left) { 14 | left = p->left; 15 | } 16 | if(p->left) { 17 | p->left->next = p->right; 18 | } else { 19 | break; 20 | } 21 | 22 | if(p->next) { 23 | p->right->next = p->next->left; 24 | p = p->next; 25 | continue; 26 | } else { 27 | p = left; 28 | left = NULL; 29 | } 30 | } 31 | } 32 | }; 33 | 34 | int main() { 35 | TreeLinkNode n1(1); 36 | TreeLinkNode n2(2); 37 | TreeLinkNode n3(3); 38 | TreeLinkNode n4(4); 39 | TreeLinkNode n5(5); 40 | TreeLinkNode n6(6); 41 | TreeLinkNode n7(7); 42 | 43 | n1.left = &n2; 44 | n1.right = &n3; 45 | 46 | n2.left = &n4; 47 | n2.right = &n5; 48 | 49 | n3.left = &n6; 50 | n3.right = &n7; 51 | 52 | Solution sln; 53 | 54 | sln.connect(&n1); 55 | 56 | TreeLinkNode* p = &n1; 57 | TreeLinkNode* next = p->next; 58 | while(p) { 59 | cout << p->val << "\t"; 60 | next = p->next; 61 | while(next) { 62 | cout << next->val << "\t"; 63 | next = next->next; 64 | } 65 | cout << endl; 66 | p = p->left; 67 | } 68 | 69 | return 0; 70 | } -------------------------------------------------------------------------------- /interleaving-string.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | bool isInterleave(string s1, string s2, string s3) { 6 | if(s1.size() + s2.size() != s3.size()) { 7 | return false; 8 | } 9 | 10 | vector > dp; 11 | dp.resize(s1.size() + 1); 12 | for(int i = 0; i <= s1.size(); i++) { 13 | dp[i].resize(s2.size() + 1, false); 14 | } 15 | 16 | dp[0][0] = true; 17 | 18 | for(int i = 1; i <= s1.size(); i++) { 19 | if(s1[i - 1] == s3[i - 1]) { 20 | dp[i][0] = true; 21 | } 22 | } 23 | 24 | for(int j = 1; j <= s2.size(); j++) { 25 | if(s2[j - 1] == s3[j - 1]) { 26 | dp[0][j] = true; 27 | } 28 | } 29 | 30 | for(int i = 1; i <= s1.size(); i++) { 31 | char c1 = s1[i - 1]; 32 | for(int j = 1; j <= s2.size(); j++) { 33 | char c2 = s2[j - 1]; 34 | 35 | char c3 = s3[i + j - 1]; 36 | 37 | if(c1 == c3) { 38 | dp[i][j] = dp[i][j] || dp[i - 1][j]; 39 | } 40 | if(c2 == c3) { 41 | dp[i][j] = dp[i][j] || dp[i][j - 1]; 42 | } 43 | } 44 | } 45 | 46 | return dp[s1.size()][s2.size()]; 47 | } 48 | }; 49 | 50 | int main() { 51 | Solution sln; 52 | 53 | string s1 = "aabcc"; 54 | string s2 = "dbbca"; 55 | 56 | cout << sln.isInterleave(s1, s2, "aadbbcbcac") << endl; 57 | cout << sln.isInterleave(s1, s2, "aadbbbaccc") << endl; 58 | 59 | return 0; 60 | } -------------------------------------------------------------------------------- /restore-ip-addresses.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | vector vs; 6 | vector ps; 7 | 8 | vector restoreIpAddresses(string s) { 9 | ps.resize(4); 10 | dfs(s, 0, 0); 11 | return vs; 12 | } 13 | 14 | void dfs(const string& s, int start, int dep) { 15 | if(dep == 4) { 16 | if(start == s.size()) { 17 | string ss; 18 | for(int i = 0; i < ps.size(); i++) { 19 | ss.append(ps[i]); 20 | if(i != ps.size() - 1) { 21 | ss.append("."); 22 | } 23 | } 24 | vs.push_back(ss); 25 | } 26 | return; 27 | } 28 | 29 | for(int i = start; i < s.size(); i++) { 30 | auto sub = s.substr(start, i - start + 1); 31 | if(check(sub)) { 32 | ps[dep] = sub; 33 | 34 | dfs(s, i + 1, dep + 1); 35 | } 36 | } 37 | } 38 | 39 | bool check(const string& s) { 40 | switch(s.size()) { 41 | case 1: 42 | return s >= "0" && s <= "9"; 43 | case 2: 44 | return s >= "10" && s <= "99"; 45 | case 3: 46 | return s >= "100" && s <= "255"; 47 | default: 48 | return false; 49 | } 50 | } 51 | }; 52 | 53 | int main() { 54 | Solution sln; 55 | 56 | auto v = sln.restoreIpAddresses("25525511135"); 57 | for(int i = 0; i < v.size(); i++) { 58 | cout << v[i] << endl; 59 | } 60 | 61 | return 0; 62 | } -------------------------------------------------------------------------------- /set-matrix-zeroes.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | void setZeroes(vector > &matrix) { 6 | if(matrix.empty() || matrix[0].empty()) { 7 | return; 8 | } 9 | 10 | int row = matrix.size(); 11 | int col = matrix[0].size(); 12 | 13 | bool zeroRow, zeroCol; 14 | zeroRow = false; 15 | zeroCol = false; 16 | for(int i = 0; i < col; i++) { 17 | if(matrix[0][i] == 0) { 18 | zeroRow = true; 19 | break; 20 | } 21 | } 22 | 23 | for(int j = 0; j < row; j++) { 24 | if(matrix[j][0] == 0) { 25 | zeroCol = true; 26 | break; 27 | } 28 | } 29 | 30 | for(int i = 1; i < row; i++) { 31 | for(int j = 1; j < col; j++) { 32 | if(matrix[i][j] == 0) { 33 | matrix[i][0] = 0; 34 | matrix[0][j] = 0; 35 | } 36 | } 37 | } 38 | 39 | for(int i = 1; i < row; i++) { 40 | for(int j = 1; j < col; j++) { 41 | if(matrix[i][0] == 0 || matrix[0][j] == 0) { 42 | matrix[i][j] = 0; 43 | } 44 | } 45 | } 46 | 47 | if(zeroRow) { 48 | for(int i = 0; i < col; i++) { 49 | matrix[0][i] = 0; 50 | } 51 | } 52 | 53 | if(zeroCol) { 54 | for(int i = 0; i < row; i++) { 55 | matrix[i][0] = 0; 56 | } 57 | } 58 | } 59 | }; 60 | 61 | int main() { 62 | return 0; 63 | } -------------------------------------------------------------------------------- /valid-parentheses.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | bool isLeft(char c) { 6 | switch(c) { 7 | case '(': 8 | case '{': 9 | case '[': 10 | return true; 11 | default: 12 | return false; 13 | } 14 | } 15 | 16 | bool isPair(char c1, char c2) { 17 | return (c1 == '(' && c2 == ')') || 18 | (c1 == '{' && c2 == '}') || 19 | (c1 == '[' && c2 == ']'); 20 | } 21 | 22 | bool isValid(string s) { 23 | if(s.empty()) { 24 | return true; 25 | } 26 | vector v; 27 | v.push_back(s[0]); 28 | 29 | for(int i = 1; i < s.size(); i++) { 30 | switch(s[i]) { 31 | case '(': 32 | case '{': 33 | case '[': 34 | if(v.empty() || isLeft(v.back())) { 35 | v.push_back(s[i]); 36 | } else { 37 | return false; 38 | } 39 | break; 40 | case ')': 41 | case '}': 42 | case ']': 43 | if(!v.empty() && isPair(v.back(), s[i])) { 44 | v.pop_back(); 45 | } else { 46 | return false; 47 | } 48 | break; 49 | } 50 | } 51 | return v.empty(); 52 | } 53 | }; 54 | 55 | int main() { 56 | Solution sln; 57 | 58 | cout << sln.isValid("()[]{}") << endl; 59 | cout << sln.isValid("()[{]}") << endl; 60 | 61 | return 0; 62 | } -------------------------------------------------------------------------------- /valid-sudoku.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | bool isValidSudoku(vector > &board) { 6 | vector flag(10, false); 7 | 8 | for(int i = 0; i < 9; i++) { 9 | fill(flag.begin(), flag.end(), false); 10 | for(int j = 0; j < 9; j++) { 11 | if(!setFlag(flag, board[i][j])) { 12 | return false; 13 | } 14 | } 15 | } 16 | 17 | for(int j = 0; j < 9; j++) { 18 | fill(flag.begin(), flag.end(), false); 19 | 20 | for(int i = 0; i < 9; i++) { 21 | if (!setFlag(flag, board[i][j])) 22 | { 23 | return false; 24 | } 25 | } 26 | } 27 | 28 | for(int i = 0; i < 3; i++) { 29 | for(int j = 0; j < 3; j++) { 30 | fill(flag.begin(), flag.end(), false); 31 | 32 | for(int m = 0; m < 3; m++) { 33 | for(int n = 0; n < 3; n++) { 34 | if(!setFlag(flag, board[i * 3 + m][j * 3 + n])){ 35 | return false; 36 | } 37 | } 38 | } 39 | } 40 | } 41 | return true; 42 | } 43 | 44 | bool setFlag(vector& flag, char c) { 45 | if(c == '.') { 46 | return true; 47 | } 48 | 49 | int i = c - '0'; 50 | if(flag[i]) { 51 | return false; 52 | } else { 53 | flag[i] = true; 54 | return true; 55 | } 56 | } 57 | }; 58 | 59 | int main() { 60 | return 0; 61 | } -------------------------------------------------------------------------------- /longest-palindromic-substring.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | // Transform S into T. 6 | // For example, S = "abba", T = "^#a#b#b#a#$". 7 | // ^ and $ signs are sentinels appended to each end to avoid bounds checking 8 | string preProcess(string s) { 9 | int n = s.length(); 10 | if (n == 0) return "^$"; 11 | string ret = "^"; 12 | for (int i = 0; i < n; i++) 13 | ret += "#" + s.substr(i, 1); 14 | 15 | ret += "#$"; 16 | return ret; 17 | } 18 | 19 | string longestPalindrome(string s) { 20 | string T = preProcess(s); 21 | int n = T.length(); 22 | int *P = new int[n]; 23 | int C = 0, R = 0; 24 | for (int i = 1; i < n-1; i++) { 25 | int i_mirror = 2*C-i; // equals to i' = C - (i-C) 26 | 27 | P[i] = (R > i) ? min(R-i, P[i_mirror]) : 0; 28 | 29 | // Attempt to expand palindrome centered at i 30 | while (T[i + 1 + P[i]] == T[i - 1 - P[i]]) 31 | P[i]++; 32 | 33 | // If palindrome centered at i expand past R, 34 | // adjust center based on expanded palindrome. 35 | if (i + P[i] > R) { 36 | C = i; 37 | R = i + P[i]; 38 | } 39 | } 40 | 41 | // Find the maximum element in P. 42 | int maxLen = 0; 43 | int centerIndex = 0; 44 | for (int i = 1; i < n-1; i++) { 45 | if (P[i] > maxLen) { 46 | maxLen = P[i]; 47 | centerIndex = i; 48 | } 49 | } 50 | delete[] P; 51 | 52 | return s.substr((centerIndex - 1 - maxLen)/2, maxLen); 53 | } 54 | }; 55 | 56 | int main() { 57 | return 0; 58 | } -------------------------------------------------------------------------------- /text-justification.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | vector fullJustify(vector &words, int L) { 6 | vector v; 7 | int len = words.size(); 8 | int i = 0; 9 | while(i < len) { 10 | int rowLen = 0; 11 | int j = i; 12 | while(j < len && rowLen + words[j].size() <= L) { 13 | rowLen += (words[j].size() + 1); 14 | j++; 15 | } 16 | 17 | if(j - i == 1) { 18 | v.push_back(words[i]); 19 | v.back().append(L - words[i].size(), ' '); 20 | i = j; 21 | continue; 22 | } 23 | 24 | int charaLen = rowLen - (j - i); 25 | int meanSpace = j < len ? (L - charaLen) / (j - i - 1) : 1; 26 | int leftSpace = j < len ? (L - charaLen) % (j - i - 1) : L - charaLen - (j - i -1); 27 | 28 | string tmp; 29 | for(int k = i; k < j - 1; k++) { 30 | tmp += words[k]; 31 | tmp.append(meanSpace, ' '); 32 | if(j < len && leftSpace > 0) { 33 | tmp.push_back(' '); 34 | leftSpace--; 35 | } 36 | } 37 | 38 | tmp += words[j - 1]; 39 | if(leftSpace > 0) { 40 | tmp.append(leftSpace, ' '); 41 | } 42 | v.push_back(tmp); 43 | i = j; 44 | } 45 | 46 | return v; 47 | } 48 | }; 49 | 50 | int main() { 51 | vector w({"This", "is", "an", "example", "of", "text", "justification."}); 52 | 53 | Solution sln; 54 | auto v = sln.fullJustify(w, 16); 55 | 56 | printVector(v); 57 | return 0; 58 | } -------------------------------------------------------------------------------- /path-sum-ii.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | vector > sums; 6 | vector > pathSum(TreeNode *root, int sum) { 7 | if(!root) { 8 | return sums; 9 | } 10 | vector vals; 11 | 12 | vals.push_back(root->val); 13 | checkSum(root, sum, vals); 14 | return sums; 15 | } 16 | 17 | void checkSum(TreeNode* node, int sum, vector& vals) { 18 | if(!node->left && !node->right && node->val == sum) { 19 | sums.push_back(vals); 20 | return; 21 | } 22 | 23 | if(node->left) { 24 | vals.push_back(node->left->val); 25 | checkSum(node->left, sum - node->val, vals); 26 | vals.pop_back(); 27 | } 28 | 29 | if(node->right) { 30 | vals.push_back(node->right->val); 31 | checkSum(node->right, sum - node->val, vals); 32 | vals.pop_back(); 33 | } 34 | } 35 | }; 36 | 37 | int main() { 38 | TreeNode n1(5); 39 | TreeNode n2(4); 40 | TreeNode n3(8); 41 | TreeNode n4(11); 42 | TreeNode n5(13); 43 | TreeNode n6(4); 44 | TreeNode n7(7); 45 | TreeNode n8(2); 46 | TreeNode n9(5); 47 | TreeNode n10(1); 48 | 49 | n1.left = &n2; 50 | n1.right = &n3; 51 | 52 | n2.left = &n4; 53 | n4.left = &n7; 54 | n4.right = &n8; 55 | 56 | n3.left = &n5; 57 | n3.right = &n6; 58 | 59 | n6.left = &n9; 60 | n6.right = &n10; 61 | 62 | Solution sln; 63 | 64 | auto a = sln.pathSum(&n1, 22); 65 | 66 | for(int i = 0; i < a.size(); i++) { 67 | for(int j = 0; j < a[i].size(); j++) { 68 | cout << a[i][j] << "\t"; 69 | } 70 | cout << endl; 71 | } 72 | 73 | return 0; 74 | } -------------------------------------------------------------------------------- /word-search.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | bool exist(vector > &board, string word) { 6 | if(word.empty()) { 7 | return true; 8 | } 9 | 10 | if(board.empty() || board[0].empty()) { 11 | return false; 12 | } 13 | 14 | for(int i = 0; i < board.size(); i++) { 15 | for(int j = 0; j < board[0].size(); j++) { 16 | if(board[i][j] == word[0] && dfs(board, word, 0, i, j)) { 17 | return true; 18 | } 19 | } 20 | } 21 | return false; 22 | } 23 | 24 | bool dfs(vector > &board, string word, int level, int x, int y) { 25 | if(level == word.size() - 1) { 26 | return true; 27 | } 28 | 29 | char c = board[x][y]; 30 | board[x][y] = '#'; 31 | 32 | char w = word[level + 1]; 33 | if(x - 1 >= 0 && board[x - 1][y] == w) { 34 | if(dfs(board, word, level + 1, x - 1, y)) { 35 | return true; 36 | } 37 | } 38 | 39 | if(x + 1 < board.size() && board[x + 1][y] == w) { 40 | if(dfs(board, word, level + 1, x + 1, y)) { 41 | return true; 42 | } 43 | } 44 | 45 | if(y - 1 >= 0 && board[x][y - 1] == w) { 46 | if(dfs(board, word, level + 1, x, y - 1)) { 47 | return true; 48 | } 49 | } 50 | 51 | if(y + 1 < board[0].size() && board[x][y + 1] == w) { 52 | if(dfs(board, word, level + 1, x, y + 1)) { 53 | return true; 54 | } 55 | } 56 | 57 | board[x][y] = c; 58 | return false; 59 | } 60 | }; 61 | 62 | int main() { 63 | return 0; 64 | } -------------------------------------------------------------------------------- /longest-consecutive-sequence.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int longestConsecutive(vector &num) { 6 | unordered_set h; 7 | unordered_set::iterator it; 8 | int l = (int)num.size(); 9 | for(int i = 0; i < l; i++) { 10 | h.insert(num[i]); 11 | } 12 | 13 | int n = 0; 14 | int c = 0; 15 | int j = 0; 16 | for(int i = 0; i < l; i++) { 17 | it = h.find(num[i]); 18 | if(it != h.end()) { 19 | c = 1; 20 | h.erase(it); 21 | j = num[i]; 22 | while(true) { 23 | ++j; 24 | it = h.find(j); 25 | if(it != h.end()) { 26 | h.erase(it); 27 | c++; 28 | } else { 29 | break; 30 | } 31 | } 32 | j = num[i]; 33 | while(true) { 34 | --j; 35 | it = h.find(j); 36 | if(it != h.end()) { 37 | h.erase(it); 38 | c++; 39 | } else { 40 | break; 41 | } 42 | } 43 | 44 | if(c > n) { 45 | n = c; 46 | } 47 | } 48 | } 49 | 50 | return n; 51 | } 52 | }; 53 | 54 | int main() { 55 | Solution sln; 56 | vector num; 57 | 58 | num.push_back(100); 59 | num.push_back(4); 60 | num.push_back(200); 61 | num.push_back(1); 62 | num.push_back(3); 63 | num.push_back(2); 64 | 65 | cout << sln.longestConsecutive(num) << endl; 66 | 67 | return 0; 68 | } -------------------------------------------------------------------------------- /4sum.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | vector > fourSum(vector &num, int target) { 6 | vector > vv; 7 | 8 | sort(num.begin(), num.end()); 9 | 10 | int len = num.size(); 11 | 12 | for(int i = 0; i < len - 3; i++) { 13 | if(i > 0 && num[i - 1] == num[i]) { 14 | continue; 15 | } 16 | 17 | for(int j = i + 1; j < len - 2; j++) { 18 | if(j > i + 1 && num[j - 1] == num[j]) { 19 | continue; 20 | } 21 | 22 | int start = j + 1; 23 | int end = len - 1; 24 | int target2 = target - num[i] - num[j]; 25 | while(start < end) { 26 | int sum = num[start] + num[end]; 27 | if(sum == target2) { 28 | vv.push_back(vector({num[i], num[j], num[start], num[end]})); 29 | start++; 30 | end--; 31 | 32 | while(start < end && num[start] == num[start - 1]) { 33 | start++; 34 | } 35 | 36 | while(start < end && num[end + 1] == num[end]) { 37 | end--; 38 | } 39 | } else if(sum < target2) { 40 | start++; 41 | } else { 42 | end--; 43 | } 44 | } 45 | } 46 | } 47 | 48 | return vv; 49 | } 50 | }; 51 | 52 | int main() { 53 | Solution sln; 54 | 55 | vector num({1,0,-1,0,-2,2}); 56 | auto vv = sln.fourSum(num, 0); 57 | 58 | printVector2(vv); 59 | return 0; 60 | } -------------------------------------------------------------------------------- /sort-list.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | ListNode *sortList(ListNode *head) { 6 | if(head == NULL || head->next == NULL) { 7 | return head; 8 | } 9 | 10 | ListNode* fast = head; 11 | ListNode* slow = head; 12 | 13 | while(fast->next && fast->next->next) { 14 | fast = fast->next->next; 15 | slow = slow->next; 16 | } 17 | 18 | fast = slow->next; 19 | slow->next = NULL; 20 | 21 | ListNode* p1 = sortList(head); 22 | ListNode* p2 = sortList(fast); 23 | 24 | return merge(p1, p2); 25 | } 26 | 27 | ListNode *merge(ListNode* l1, ListNode* l2) { 28 | if(!l1) { 29 | return l2; 30 | } else if (!l2) { 31 | return l1; 32 | } else if (!l1 && !l2) { 33 | return NULL; 34 | } 35 | 36 | ListNode dummy(0); 37 | ListNode* p = &dummy; 38 | 39 | while(l1 && l2) { 40 | if(l1->val < l2->val) { 41 | p->next = l1; 42 | l1 = l1->next; 43 | } else { 44 | p->next = l2; 45 | l2 = l2->next; 46 | } 47 | 48 | p = p->next; 49 | } 50 | 51 | if(l1) { 52 | p->next = l1; 53 | } else if(l2){ 54 | p->next = l2; 55 | } 56 | 57 | return dummy.next; 58 | } 59 | }; 60 | 61 | 62 | int main() { 63 | ListNode n1(6); 64 | ListNode n2(1); 65 | ListNode n3(9); 66 | 67 | ListNode n4(2); 68 | ListNode n5(7); 69 | 70 | n1.next = &n2; 71 | n2.next = &n3; 72 | n3.next = &n4; 73 | n4.next = &n5; 74 | 75 | printListNode(&n1); 76 | 77 | 78 | Solution sln; 79 | ListNode* a = sln.sortList(&n1); 80 | 81 | printListNode(a); 82 | 83 | return 0; 84 | } -------------------------------------------------------------------------------- /populating-next-right-pointers-in-each-node-ii.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | void connect(TreeLinkNode *root) { 6 | if(!root) { 7 | return; 8 | } 9 | 10 | TreeLinkNode* p = root; 11 | TreeLinkNode* first = NULL; 12 | TreeLinkNode* last = NULL; 13 | 14 | while(p) { 15 | if(!first) { 16 | if(p->left) { 17 | first = p->left; 18 | } else if(p->right) { 19 | first = p->right; 20 | } 21 | } 22 | if(p->left) { 23 | if(last) { 24 | last->next = p->left; 25 | } 26 | last = p->left; 27 | } 28 | 29 | if(p->right) { 30 | if(last) { 31 | last->next = p->right; 32 | } 33 | last = p->right; 34 | } 35 | 36 | if(p->next) { 37 | p = p->next; 38 | } else { 39 | p = first; 40 | last = NULL; 41 | first = NULL; 42 | } 43 | } 44 | } 45 | }; 46 | 47 | int main() { 48 | TreeLinkNode n1(1); 49 | TreeLinkNode n2(2); 50 | TreeLinkNode n3(3); 51 | TreeLinkNode n4(4); 52 | TreeLinkNode n5(5); 53 | TreeLinkNode n7(7); 54 | 55 | n1.left = &n2; 56 | n1.right = &n3; 57 | 58 | n2.left = &n4; 59 | n2.right = &n5; 60 | 61 | n3.right = &n7; 62 | 63 | Solution sln; 64 | 65 | sln.connect(&n1); 66 | 67 | TreeLinkNode* p = &n1; 68 | TreeLinkNode* next = p->next; 69 | while(p) { 70 | cout << p->val << "\t"; 71 | next = p->next; 72 | while(next) { 73 | cout << next->val << "\t"; 74 | next = next->next; 75 | } 76 | cout << endl; 77 | p = p->left; 78 | } 79 | 80 | return 0; 81 | } -------------------------------------------------------------------------------- /evaluate-reverse-polish-notation.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int evalRPN(vector &tokens) { 6 | vector nums; 7 | 8 | for(int i = 0; i < int(tokens.size()); i++) { 9 | if(isOperator(tokens[i])) { 10 | calc(nums, tokens[i][0]); 11 | } else { 12 | int n = atoi(tokens[i].c_str()); 13 | nums.push_back(n); 14 | } 15 | } 16 | 17 | return nums[0]; 18 | } 19 | 20 | bool isOperator(const string& str) { 21 | if(str.size() != 1) { 22 | return false; 23 | } 24 | 25 | switch(str[0]) { 26 | case '+': 27 | return true; 28 | case '-': 29 | return true; 30 | case '*': 31 | return true; 32 | case '/': 33 | return true; 34 | default: 35 | return false; 36 | } 37 | } 38 | 39 | void calc(vector& nums, char opt) { 40 | int a2 = nums.back(); 41 | nums.pop_back(); 42 | int a1 = nums.back(); 43 | nums.pop_back(); 44 | 45 | int result = 0; 46 | 47 | switch(opt) { 48 | case '+': 49 | result = a1 + a2; 50 | break; 51 | case '-': 52 | result = a1 - a2; 53 | break; 54 | case '*': 55 | result = a1 * a2; 56 | break; 57 | case '/': 58 | result = a1 / a2; 59 | break; 60 | } 61 | nums.push_back(result); 62 | } 63 | }; 64 | 65 | int main() { 66 | Solution sln; 67 | 68 | string ay1[5] = {"2", "1", "+", "3", "*"}; 69 | vector s1(ay1, ay1 + 5); 70 | 71 | string ay2[5] = {"4", "13", "5", "/", "+"}; 72 | vector s2(ay2, ay2 + 5); 73 | 74 | cout << sln.evalRPN(s1) << endl; 75 | cout << sln.evalRPN(s2) << endl; 76 | 77 | return 0; 78 | } -------------------------------------------------------------------------------- /recover-binary-search-tree.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | void recoverTree(TreeNode *root) { 6 | TreeNode* cur = 0; 7 | TreeNode* pre = 0; 8 | TreeNode* p1 = 0; 9 | TreeNode* p2 = 0; 10 | TreeNode* preCur = 0; 11 | 12 | bool found = false; 13 | 14 | if(!root) { 15 | return; 16 | } 17 | 18 | cur = root; 19 | while(cur) { 20 | if(!cur->left) { 21 | if(preCur && preCur->val > cur->val) { 22 | if(!found) { 23 | p1 = preCur; 24 | found = true; 25 | } 26 | p2 = cur; 27 | } 28 | 29 | preCur = cur; 30 | cur = cur->right; 31 | } else { 32 | pre = cur->left; 33 | while(pre->right && pre->right != cur) { 34 | pre = pre->right; 35 | } 36 | 37 | if(!pre->right) { 38 | pre->right = cur; 39 | cur = cur->left; 40 | } else { 41 | if(preCur->val > cur->val) { 42 | if(!found) { 43 | p1 = preCur; 44 | found = true; 45 | } 46 | p2 = cur; 47 | } 48 | preCur = cur; 49 | pre->right = NULL; 50 | cur = cur->right; 51 | } 52 | } 53 | } 54 | 55 | if(p1 && p2) { 56 | int t = p1->val; 57 | p1->val = p2->val; 58 | p2->val = t; 59 | } 60 | } 61 | }; 62 | 63 | int main() { 64 | TreeNode n1(2); 65 | TreeNode n2(3); 66 | TreeNode n3(1); 67 | 68 | n1.left = &n2; 69 | n1.right = &n3; 70 | 71 | Solution sln; 72 | 73 | sln.recoverTree(&n1); 74 | 75 | cout << n1.val << "\t"; 76 | cout << n2.val << "\t"; 77 | cout << n3.val << endl; 78 | 79 | return 0; 80 | } -------------------------------------------------------------------------------- /max-point-on-a-line.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | struct Point { 4 | int x; 5 | int y; 6 | Point():x(0),y(0){} 7 | Point(int a, int b) : x(a), y(b) {} 8 | }; 9 | 10 | class Solution { 11 | public: 12 | int maxPoints(vector &points) { 13 | map slopeNums; 14 | double maxSlope = numeric_limits::infinity(); 15 | 16 | int maxCount = 0; 17 | 18 | if(points.empty()) { 19 | return 0; 20 | } else if(points.size() == 1) { 21 | return 1; 22 | } 23 | 24 | for (int i = 0; i < (int)points.size() - 1; i++) { 25 | slopeNums.clear(); 26 | 27 | Point x1 = points[i]; 28 | 29 | int samePoints = 0; 30 | 31 | int cnt = 1; 32 | 33 | for(int j = i + 1; j < (int)points.size(); j++) { 34 | Point x2 = points[j]; 35 | 36 | double slope = maxSlope; 37 | 38 | if(x1.x != x2.x) { 39 | slope = (double)(x2.y - x1.y) / (double)(x2.x - x1.x); 40 | } else if(x1.y == x2.y) { 41 | samePoints++; 42 | continue; 43 | } 44 | 45 | int num = slopeNums[slope]; 46 | if(num == 0) { 47 | slopeNums[slope] = 2; 48 | num = 2; 49 | } else { 50 | num++; 51 | slopeNums[slope] = num; 52 | } 53 | if(num > cnt) { 54 | cnt = num; 55 | } 56 | } 57 | 58 | if((cnt + samePoints)> maxCount) { 59 | maxCount = cnt + samePoints; 60 | } 61 | } 62 | 63 | return maxCount; 64 | } 65 | }; 66 | 67 | int main() { 68 | Solution sln; 69 | vector points; 70 | points.push_back(Point(0, 0)); 71 | points.push_back(Point(1, 1)); 72 | points.push_back(Point(0, 0)); 73 | int n = sln.maxPoints(points); 74 | cout << n << endl; 75 | return 0; 76 | } -------------------------------------------------------------------------------- /word-ladder.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int ladderLength(string start, string end, unordered_set &dict) { 6 | deque vs; 7 | vs.push_back(start); 8 | 9 | int n = 1; 10 | 11 | while(!vs.empty()) { 12 | size_t count = vs.size(); 13 | for(size_t ct = 0; ct < count; ct++) { 14 | string tmp = vs.front(); 15 | vs.pop_front(); 16 | 17 | if(!tmp.empty()) { 18 | for(size_t i = 0; i < tmp.size(); i++) 19 | { 20 | char t = tmp[i]; 21 | for(char c = 'a'; c <= 'z'; c++) { 22 | if(c == t) { 23 | continue; 24 | } 25 | 26 | tmp[i] = c; 27 | if(tmp == end) { 28 | return n + 1; 29 | } 30 | 31 | if(dict.find(tmp) != dict.end()) { 32 | vs.push_back(tmp); 33 | dict.erase(tmp); 34 | } 35 | } 36 | 37 | tmp[i] = t; 38 | } 39 | } 40 | } 41 | n++; 42 | } 43 | 44 | return 0; 45 | } 46 | }; 47 | 48 | int main() { 49 | Solution sln; 50 | unordered_set dict({"si","go","se","cm","so","ph","mt","db","mb","sb","kr","ln","tm","le","av","sm","ar","ci","ca","br","ti","ba","to","ra","fa","yo","ow","sn","ya","cr","po","fe","ho","ma","re","or","rn","au","ur","rh","sr","tc","lt","lo","as","fr","nb","yb","if","pb","ge","th","pm","rb","sh","co","ga","li","ha","hz","no","bi","di","hi","qa","pi","os","uh","wm","an","me","mo","na","la","st","er","sc","ne","mn","mi","am","ex","pt","io","be","fm","ta","tb","ni","mr","pa","he","lr","sq","ye"}); 51 | string start = "qa"; 52 | string end = "sq"; 53 | 54 | cout << sln.ladderLength(start, end, dict) << endl; 55 | 56 | return 0; 57 | } -------------------------------------------------------------------------------- /word-break-ii.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | vector wordBreak(string s, set &dict) { 6 | vector vals; 7 | 8 | int len = (int)s.size(); 9 | vector > words; 10 | words.resize(len); 11 | for(int i = 0; i < len; i++) { 12 | words[i].resize(len + 1, 0); 13 | } 14 | 15 | for(int i = 1; i <= len; i++) { 16 | for(int j = 0; j < len; j++) { 17 | if(dict.find(s.substr(j, i)) != dict.end()) { 18 | words[j][i] = 1; 19 | continue; 20 | } 21 | for(int k = 1; k < i; k++) { 22 | if(words[j][k] && words[j + k][i - k]) { 23 | words[j][i] = 2; 24 | break; 25 | } 26 | } 27 | } 28 | } 29 | 30 | if(words[0][len] == 0) { 31 | return vals; 32 | } 33 | 34 | string val; 35 | 36 | dfs(s, 0, val, words, vals); 37 | return vals; 38 | } 39 | 40 | void dfs(const string& s, int start, string& val, vector >&words, vector& vals) { 41 | int len = (int)s.size(); 42 | if(start == len) { 43 | vals.push_back(val); 44 | return; 45 | } 46 | 47 | for(int i = 1; i <= len - start;i++) { 48 | if(words[start][i] == 1) { 49 | int oldLen = (int)val.size(); 50 | if(oldLen != 0) { 51 | val.append(" "); 52 | } 53 | val.append(s.substr(start, i)); 54 | 55 | dfs(s, start + i, val, words, vals); 56 | val.erase(oldLen, string::npos); 57 | } 58 | } 59 | } 60 | }; 61 | 62 | int main() { 63 | string s = "catsanddog"; 64 | set dict; 65 | dict.insert("cat"); 66 | dict.insert("cats"); 67 | dict.insert("and"); 68 | dict.insert("sand"); 69 | dict.insert("dog"); 70 | 71 | Solution sln; 72 | 73 | vector a = sln.wordBreak(s, dict); 74 | for(int i = 0; i < (int)a.size(); i++) { 75 | cout << a[i] << endl; 76 | } 77 | 78 | return 0; 79 | } -------------------------------------------------------------------------------- /leetcode.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | 19 | using namespace std; 20 | 21 | struct ListNode { 22 | int val; 23 | ListNode *next; 24 | ListNode(int x): val(x), next(NULL) {} 25 | }; 26 | 27 | 28 | void printListNode(ListNode* a) { 29 | cout << "list nodes: "; 30 | while(a) { 31 | cout << a->val << "\t"; 32 | a = a->next; 33 | } 34 | cout << endl; 35 | } 36 | 37 | ListNode* createListNode(const vector& v) { 38 | ListNode dummy(0); 39 | ListNode* p = &dummy; 40 | 41 | for(int i = 0; i < v.size(); i++) { 42 | p->next = new ListNode(v[i]); 43 | p = p->next; 44 | } 45 | 46 | return dummy.next; 47 | } 48 | 49 | struct TreeNode { 50 | int val; 51 | TreeNode *left; 52 | TreeNode *right; 53 | TreeNode(int x) : val(x), left(NULL), right(NULL) {} 54 | }; 55 | 56 | struct RandomListNode { 57 | int label; 58 | RandomListNode *next, *random; 59 | RandomListNode(int x) : label(x), next(NULL), random(NULL) {} 60 | }; 61 | 62 | struct UndirectedGraphNode { 63 | int label; 64 | vector neighbors; 65 | UndirectedGraphNode(int x) : label(x) {}; 66 | }; 67 | 68 | struct TreeLinkNode { 69 | int val; 70 | TreeLinkNode *left; 71 | TreeLinkNode *right; 72 | TreeLinkNode *next; 73 | TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} 74 | }; 75 | 76 | template 77 | void printVector(const vector& a) { 78 | for(int i = 0; i < a.size(); i++) { 79 | cout << a[i] << "\t"; 80 | } 81 | 82 | cout << endl; 83 | } 84 | 85 | template 86 | void printVector2(const vector >& a) { 87 | for(int i = 0; i < a.size(); i++) { 88 | printVector(a[i]); 89 | } 90 | } 91 | 92 | struct Interval { 93 | int start; 94 | int end; 95 | Interval() : start(0), end(0) {} 96 | Interval(int s, int e) : start(s), end(e) {} 97 | }; -------------------------------------------------------------------------------- /surrounded-regions.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | void solve(vector > &board) { 6 | if(board.empty()) { 7 | return; 8 | } 9 | 10 | int row = (int)board.size(); 11 | int col = (int)board[0].size(); 12 | 13 | 14 | for(int j = 0; j < col; j++) { 15 | if(board[0][j] == 'O') { 16 | board[0][j] = '#'; 17 | dfs(board, 0, j, row, col); 18 | } 19 | 20 | if(board[row - 1][j] == 'O') { 21 | board[row - 1][j] = '#'; 22 | dfs(board, row - 1, j, row, col); 23 | } 24 | } 25 | 26 | for(int i = 0; i < row; i++) { 27 | if(board[i][0] == 'O') { 28 | board[i][0] = '#'; 29 | dfs(board, i, 0, row, col); 30 | } 31 | 32 | if(board[i][col - 1] == 'O') { 33 | board[i][col - 1] = '#'; 34 | dfs(board, i, col - 1, row, col); 35 | } 36 | } 37 | 38 | for(int i = 0; i < row; i++) { 39 | for(int j = 0; j < col; j++) { 40 | if(board[i][j] == '#') 41 | { 42 | board[i][j] = 'O'; 43 | } else if(board[i][j] == 'O') { 44 | board[i][j] = 'X'; 45 | } 46 | } 47 | } 48 | } 49 | 50 | void dfs(vector > &board, int i, int j, int row, int column) { 51 | if(i > 1 && board[i - 1][j] == 'O') { 52 | board[i - 1][j] = '#'; 53 | dfs(board, i - 1, j, row, column); 54 | } 55 | 56 | if(i < row - 1 && board[i + 1][j] == 'O') { 57 | board[i + 1][j] = '#'; 58 | dfs(board, i + 1, j, row, column); 59 | } 60 | 61 | if(j > 1 && board[i][j - 1] == 'O') { 62 | board[i][j - 1] = '#'; 63 | dfs(board, i, j - 1, row, column); 64 | } 65 | 66 | if(j < column - 1 && board[i][j + 1] == 'O') { 67 | board[i][j + 1] = '#'; 68 | dfs(board, i, j + 1, row, column); 69 | } 70 | } 71 | }; 72 | 73 | int main() { 74 | Solution sln; 75 | 76 | vector > board; 77 | 78 | board.resize(4); 79 | for(size_t i = 0; i < board.size(); i++) { 80 | board[i].resize(4, 'X'); 81 | } 82 | 83 | board[1][1] = 'O'; 84 | board[1][2] = 'O'; 85 | board[2][2] = 'O'; 86 | board[3][1] = 'O'; 87 | 88 | sln.solve(board); 89 | 90 | for(size_t i = 0; i < board.size(); i++) { 91 | for(size_t j = 0; j < board[i].size(); j++) { 92 | if(board[i][j] == 'X') { 93 | cout << "X "; 94 | } else { 95 | cout << "O "; 96 | } 97 | } 98 | cout << endl; 99 | } 100 | } -------------------------------------------------------------------------------- /word-ladder-ii.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | vector> ladders; 6 | unordered_map > prevs; 7 | 8 | vector> findLadders(string start, string end, unordered_set &dict) { 9 | deque vs; 10 | 11 | bool found = false; 12 | 13 | unordered_set ds; 14 | 15 | vs.push_back(start); 16 | dict.erase(start); 17 | 18 | for(auto it = dict.begin(); it != dict.end(); ++it) { 19 | prevs[*it] = unordered_set(); 20 | } 21 | 22 | while(!found && !vs.empty()) { 23 | int cnt = vs.size(); 24 | ds.clear(); 25 | for(int i = 0; i < cnt; i++) { 26 | string tmp = vs.front(); 27 | vs.pop_front(); 28 | 29 | string prev = tmp; 30 | 31 | for(int j = 0; j < prev.size(); j++) { 32 | char t = tmp[j]; 33 | 34 | for(char c = 'a'; c <= 'z'; c++) { 35 | if(t == c) { 36 | continue; 37 | } 38 | 39 | tmp[j] = c; 40 | if(tmp == end) { 41 | prevs[tmp].insert(prev); 42 | found = true; 43 | break; 44 | } 45 | 46 | if(dict.find(tmp) != dict.end()) { 47 | prevs[tmp].insert(prev); 48 | if(ds.insert(tmp).second) { 49 | vs.push_back(tmp); 50 | } 51 | } 52 | } 53 | 54 | tmp[j] = t; 55 | } 56 | } 57 | 58 | if(found) { 59 | break; 60 | } 61 | 62 | for(auto it = ds.begin(); it != ds.end(); ++it) { 63 | dict.erase(*it); 64 | } 65 | } 66 | 67 | vector vals; 68 | dfs(end, end, vals); 69 | 70 | return ladders; 71 | } 72 | 73 | void dfs(const string& word, const string& end, vector& vals) { 74 | auto it = prevs.find(word); 75 | if(it == prevs.end()) { 76 | vector vv = vals; 77 | reverse(vv.begin(), vv.end()); 78 | vv.push_back(end); 79 | 80 | ladders.push_back(vv); 81 | return; 82 | } 83 | for(auto i = it->second.begin(); i != it->second.end(); ++i) { 84 | vals.push_back(*i); 85 | 86 | dfs(*i, end, vals); 87 | 88 | vals.pop_back(); 89 | } 90 | } 91 | 92 | }; 93 | 94 | int main() { 95 | Solution sln; 96 | 97 | unordered_set dict({"dose","ends","dine","jars","prow","soap","guns","hops","cray","hove","ella","hour","lens","jive","wiry","earl","mara","part","flue","putt","rory","bull","york","ruts","lily","vamp","bask","peer","boat","dens","lyre","jets","wide","rile","boos","down","path","onyx","mows","toke","soto","dork","nape","mans","loin","jots","male","sits","minn","sale","pets","hugo","woke","suds","rugs","vole","warp","mite","pews","lips","pals","nigh","sulk","vice","clod","iowa","gibe","shad","carl","huns","coot","sera","mils","rose","orly","ford","void","time","eloy","risk","veep","reps","dolt","hens","tray","melt","rung","rich","saga","lust","yews","rode","many","cods","rape","last","tile","nosy","take","nope","toni","bank","jock","jody","diss","nips","bake","lima","wore","kins","cult","hart","wuss","tale","sing","lake","bogy","wigs","kari","magi","bass","pent","tost","fops","bags","duns","will","tart","drug","gale","mold","disk","spay","hows","naps","puss","gina","kara","zorn","boll","cams","boas","rave","sets","lego","hays","judy","chap","live","bahs","ohio","nibs","cuts","pups","data","kate","rump","hews","mary","stow","fang","bolt","rues","mesh","mice","rise","rant","dune","jell","laws","jove","bode","sung","nils","vila","mode","hued","cell","fies","swat","wags","nate","wist","honk","goth","told","oise","wail","tels","sore","hunk","mate","luke","tore","bond","bast","vows","ripe","fond","benz","firs","zeds","wary","baas","wins","pair","tags","cost","woes","buns","lend","bops","code","eddy","siva","oops","toed","bale","hutu","jolt","rife","darn","tape","bold","cope","cake","wisp","vats","wave","hems","bill","cord","pert","type","kroc","ucla","albs","yoko","silt","pock","drub","puny","fads","mull","pray","mole","talc","east","slay","jamb","mill","dung","jack","lynx","nome","leos","lade","sana","tike","cali","toge","pled","mile","mass","leon","sloe","lube","kans","cory","burs","race","toss","mild","tops","maze","city","sadr","bays","poet","volt","laze","gold","zuni","shea","gags","fist","ping","pope","cora","yaks","cosy","foci","plan","colo","hume","yowl","craw","pied","toga","lobs","love","lode","duds","bled","juts","gabs","fink","rock","pant","wipe","pele","suez","nina","ring","okra","warm","lyle","gape","bead","lead","jane","oink","ware","zibo","inns","mope","hang","made","fobs","gamy","fort","peak","gill","dino","dina","tier"}); 98 | 99 | auto a = sln.findLadders("nape", "mild", dict); 100 | cout << "---------" << endl; 101 | for(int i = 0; i < a.size(); i++) { 102 | for(int j = 0; j < a[i].size(); j++) { 103 | cout << a[i][j] << "\t"; 104 | } 105 | 106 | cout << endl; 107 | } 108 | 109 | // cout << "---------" << endl; 110 | 111 | // sln.ladders.clear(); 112 | // sln.prevs.clear(); 113 | 114 | // dict = {"hot","dog","dot"}; 115 | // a = sln.findLadders("hot", "dog", dict); 116 | // for(int i = 0; i < a.size(); i++) { 117 | // for(int j = 0; j < a[i].size(); j++) { 118 | // cout << a[i][j] << "\t"; 119 | // } 120 | 121 | // cout << endl; 122 | // } 123 | 124 | return 0; 125 | } --------------------------------------------------------------------------------