├── .gitignore ├── Triangle └── Triangle.cpp ├── UniqueBinarySearchTrees └── UniqueBinarySearchTrees.cpp ├── RemoveElement └── RemoveElement.cpp ├── RemoveDuplicatesfromSortedArray └── RemoveDuplicatesfromSortedArray.cpp ├── Pow(x, n) └── Pow(x, n).cpp ├── LengthofLastWord └── LengthofLastWord.cpp ├── BestTimetoBuyandSellStock └── BestTimetoBuyandSellStock.cpp ├── ReverseInteger └── ReverseInteger.cpp ├── FirstMissingPositive └── FirstMissingPositive.cpp ├── PalindromeNumber └── PalindromeNumber.cpp ├── Sqrt(x) └── Sqrt(x).cpp ├── UniquePaths └── UniquePaths.cpp ├── README.md ├── NextPermutation └── NextPermutation.cpp ├── SearchInsertPosition └── SearchInsertPosition.cpp ├── JumpGame └── JumpGame.cpp ├── MergeSortedArray └── MergeSortedArray.cpp ├── LongestCommonPrefix └── LongestCommonPrefix.cpp ├── MaximumDepthofBinaryTree └── MaximumDepthofBinaryTree.cpp ├── MaximumProductSubarray └── MaximumProductSubarray.cpp ├── RotateImage └── RotateImage.cpp ├── N-QueensII └── N-QueensII.cpp ├── JumpGameII └── JumpGameII.cpp ├── LongestSubstringWithoutRepeatingCharacters └── LongestSubstringWithoutRepeatingCharacters.cpp ├── Pascal'sTriangle └── Pascal'sTriangle.cpp ├── PlusOne └── PlusOne.cpp ├── ContainerWithMostWater └── ContainerWithMostWater.cpp ├── Anagrams └── Anagrams.cpp ├── DecodeWays └── DecodeWays.cpp ├── Pascal'sTriangleII └── Pascal'sTriangleII.cpp ├── Permutations └── Permutations.cpp ├── ZigZagConversion └── ZigZagConversion.cpp ├── DistinctSubsequences └── DistinctSubsequences.cpp ├── RemoveDuplicatesfromSortedArrayII └── RemoveDuplicatesfromSortedArrayII.cpp ├── RemoveDuplicatesfromSortedList └── RemoveDuplicatesfromSortedList.cpp ├── SameTree └── SameTree.cpp ├── RomantoInteger └── RomantoInteger.cpp ├── MinimumDepthofBinaryTree └── MinimumDepthofBinaryTree.cpp ├── Subsets └── Subsets.cpp ├── GrayCode └── GrayCode.cpp ├── BalancedBinaryTree └── BalancedBinaryTree.cpp ├── CountandSay └── CountandSay.cpp ├── Combinations └── Combinations.cpp ├── ValidParentheses └── ValidParentheses.cpp ├── PopulatingNextRightPointersinEachNode └── PopulatingNextRightPointersinEachNode.cpp ├── EditDistance └── EditDistance.cpp ├── ValidSudoku └── ValidSudoku.cpp ├── PalindromePartitioningII └── PalindromePartitioningII.cpp ├── SearchinRotatedSortedArray └── SearchinRotatedSortedArray.cpp ├── BestTimetoBuyandSellStockIII └── BestTimetoBuyandSellStockIII.cpp ├── GenerateParentheses └── GenerateParentheses.cpp ├── ConvertSortedArraytoBinarySearchTree └── ConvertSortedArraytoBinarySearchTree.cpp ├── 3SumClosest └── 3SumClosest.cpp ├── DivideTwoIntegers └── DivideTwoIntegers.cpp ├── RegularExpressionMatching └── RegularExpressionMatching.cpp ├── LongestPalindromicSubstring └── LongestPalindromicSubstring.cpp ├── AddBinary └── AddBinary.cpp ├── ClimbingStairs └── ClimbingStairs.cpp ├── RemoveDuplicatesfromSortedListII └── RemoveDuplicatesfromSortedListII.cpp ├── ImplementstrStr └── ImplementstrStr.cpp ├── RemoveNthNodeFromEndofList └── RemoveNthNodeFromEndofList.cpp ├── SymmetricTree ├── SymmetricTree_recursively.cpp └── SymmetricTree_iteratively.cpp ├── ValidPalindrome └── ValidPalindrome.cpp ├── SwapNodesinPairs └── SwapNodesinPairs.cpp ├── SumRoottoLeafNumbers └── SumRoottoLeafNumbers.cpp ├── StringtoInteger(atoi) └── StringtoInteger(atoi).cpp ├── PermutationSequence └── PermutationSequence.cpp ├── ReverseLinkedListII └── ReverseLinkedListII.cpp ├── PathSum └── PathSum.cpp ├── UniquePathsII └── UniquePathsII.cpp ├── BinaryTreeMaximumPathSum └── BinaryTreeMaximumPathSum.cpp ├── CloneGraph └── CloneGraph.cc ├── MergeIntervals └── MergeIntervals.cpp ├── SimplifyPath └── SimplifyPath.cpp ├── SearchinRotatedSortedArrayII └── SearchinRotatedSortedArrayII.cpp ├── LetterCombinationsofaPhoneNumber └── LetterCombinationsofaPhoneNumber.cpp ├── SubsetsII └── SubsetsII.cpp ├── BinaryTreePreorderTraversal └── BinaryTreePreorderTraversal.cpp ├── RestoreIPAddresses └── RestoreIPAddresses.cpp ├── TwoSum └── TwoSum.cpp ├── SortColors └── SortColors.cpp ├── IntegertoRoman └── IntegertoRoman.cpp ├── PartitionList └── PartitionList.cpp ├── SpiralMatrixII └── SpiralMatrixII.cpp ├── SubstringwithConcatenationofAllWords └── SubstringwithConcatenationofAllWords.cpp ├── RotateList └── RotateList.cpp ├── WordLadder └── WordLadder.cpp ├── N-Queens └── N-Queens.cpp ├── PathSumII └── PathSumII.cpp ├── LargestRectangleinHistogram └── LargestRectangleinHistogram.cpp ├── Searcha2DMatrix └── Searcha2DMatrix.cpp ├── ConstructBinaryTreefromInorderandPostorderTraversal └── ConstructBinaryTreefromInorderandPostorderTraversal.cpp ├── MinimumWindowSubstring └── MinimumWindowSubstring.cpp ├── ConstructBinaryTreefromPreorderandInorderTraversal └── ConstructBinaryTreefromPreorderandInorderTraversal.cpp ├── MergeTwoSortedLists └── MergeTwoSortedLists.cpp ├── CombinationSumII └── CombinationSumII.cpp ├── ScrambleString └── ScrambleString.cpp ├── SpiralMatrix └── SpiralMatrix.cpp ├── MedianofTwoSortedArrays └── MedianofTwoSortedArrays.cpp ├── EvaluateReversePolishNotation └── EvaluateReversePolishNotation.cpp ├── SurroundedRegions └── SurroundedRegions.cpp ├── CombinationSum └── CombinationSum.cpp ├── InterleavingString └── InterleavingString.cpp ├── SearchforaRange └── SearchforaRange.cpp ├── UniqueBinarySearchTreesII └── UniqueBinarySearchTreesII.cpp ├── PalindromePartitioning └── PalindromePartitioning.cpp ├── ConvertSortedListtoBinarySearchTree └── ConvertSortedListtoBinarySearchTree.cpp ├── MultiplyStrings └── MultiplyStrings.cpp ├── 3Sum └── 3Sum.cpp ├── InsertInterval └── InsertInterval.cpp ├── MergekSortedLists └── MergekSortedLists.cpp ├── LongestValidParentheses └── LongestValidParentheses.cpp ├── BinaryTreeLevelOrderTraversal └── BinaryTreeLevelOrderTraversal.cpp ├── RecoverBinarySearchTree └── RecoverBinarySearchTree.cpp ├── BestTimetoBuyandSellStockII └── BestTimetoBuyandSellStockII.cpp ├── BinaryTreeLevelOrderTraversalII └── BinaryTreeLevelOrderTraversalII.cpp ├── MaximumSubarray └── MaximumSubarray.cpp ├── LRUCache └── LRUCache.cc ├── SetMatrixZeroes └── SetMatrixZeroes.cpp ├── PopulatingNextRightPointersinEachNodeII └── PopulatingNextRightPointersinEachNodeII.cpp ├── BinaryTreePostorderTraversal └── BinaryTreePostorderTraversal.cc ├── WildcardMatching └── WildcardMatching.cpp ├── BinaryTreeZigzagLevelOrderTraversal └── BinaryTreeZigzagLevelOrderTraversal.cpp ├── MinimumPathSum └── MinimumPathSum.cpp ├── LongestConsecutiveSequence └── LongestConsecutiveSequence.cpp ├── ReverseNodesink-Group └── ReverseNodesink-Group.cpp ├── AddTwoNumbers └── AddTwoNumbers.cpp ├── TrappingRainWater └── TrappingRainWater.cpp ├── PermutationsII └── PermutationsII.cpp ├── ReverseWordsInAString └── ReverseWordsInAString.cpp ├── MaximalRectangle └── MaximalRectangle.cpp ├── ValidNumber └── ValidNumber.cpp ├── SudokuSolver └── SudokuSolver.cpp ├── SortList └── SortList.cc ├── WordSearch └── WordSearch.cpp ├── BinaryTreeInorderTraversal └── BinaryTreeInorderTraversal.cpp ├── MaxPointsOnALine └── MaxPointsOnALine.cpp ├── FlattenBinaryTreetoLinkedList └── FlattenBinaryTreetoLinkedList.cpp ├── TextJustification └── TextJustification.cpp ├── ValidateBinarySearchTree └── ValidateBinarySearchTree.cpp ├── 4Sum └── 4Sum.cpp └── WordLadderII └── WordLadderII.cpp /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files 2 | *.slo 3 | *.lo 4 | *.o 5 | 6 | # Compiled Dynamic libraries 7 | *.so 8 | *.dylib 9 | 10 | # Compiled Static libraries 11 | *.lai 12 | *.la 13 | *.a 14 | -------------------------------------------------------------------------------- /Triangle/Triangle.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minimumTotal(vector > &triangle) { 4 | int level = triangle.size(); 5 | vector dp(level + 1, 0); 6 | for (int i = level - 1; i >= 0; i--) { 7 | for (int j = 0; j <= i; j++) { 8 | dp[j] = triangle[i][j] + min(dp[j], dp[j+1]); 9 | } 10 | } 11 | return dp[0]; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /UniqueBinarySearchTrees/UniqueBinarySearchTrees.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numTrees(int n) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | 7 | vector dp(n + 1, 0); 8 | dp[0] = dp[1] = 1; 9 | for (int i = 2; i <= n; i++) { 10 | for (int j = 0; j < i; j++) 11 | dp[i] += dp[j] * dp[i-j-1]; 12 | } 13 | return dp[n]; 14 | } 15 | }; -------------------------------------------------------------------------------- /RemoveElement/RemoveElement.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int removeElement(int A[], int n, int elem) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | 7 | int low = -1, high; 8 | for (high = 0; high < n; high++) { 9 | if (A[high] != elem) { 10 | low += 1; 11 | A[low] = A[high]; 12 | } 13 | } 14 | return low + 1; 15 | } 16 | }; -------------------------------------------------------------------------------- /RemoveDuplicatesfromSortedArray/RemoveDuplicatesfromSortedArray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int removeDuplicates(int A[], int n) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | if (n == 0) return 0; 7 | 8 | int low = 0; 9 | for (int high = 1; high < n; high++) { 10 | if (A[low] != A[high]) 11 | A[++low] = A[high]; 12 | } 13 | return low + 1; 14 | } 15 | }; -------------------------------------------------------------------------------- /Pow(x, n)/Pow(x, n).cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | double pow(double x, int n) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | double result = 1.0; 7 | bool negative = false; 8 | if (n < 0) negative = true; 9 | while (n) { 10 | if (n & 1) 11 | result *= x; 12 | x *= x; 13 | n /= 2; 14 | } 15 | return negative ? (1.0 / result) : result; 16 | } 17 | }; -------------------------------------------------------------------------------- /LengthofLastWord/LengthofLastWord.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int lengthOfLastWord(const char *s) { 4 | int curr = 0; 5 | const char* p = s; 6 | while (*p != '\0') { 7 | if (*p == ' ') { 8 | p++; 9 | } else { 10 | curr = 0; 11 | while (*p != '\0' && *p != ' ') { 12 | p++; 13 | curr++; 14 | } 15 | } 16 | } 17 | return curr; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /BestTimetoBuyandSellStock/BestTimetoBuyandSellStock.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(vector &prices) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | 7 | int minval = 0x3FFFFFFF; 8 | int maxprofit = 0; 9 | for (size_t i = 0; i < prices.size(); i++) { 10 | minval = min(minval, prices[i]); 11 | maxprofit = max(maxprofit, prices[i] - minval); 12 | } 13 | return maxprofit; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /ReverseInteger/ReverseInteger.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int reverse(int x) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | 7 | bool minus = false; 8 | if (x < 0) { 9 | x = -x; 10 | minus = true; 11 | } 12 | int res = 0; 13 | while (x) { 14 | res *= 10; 15 | res += x % 10; 16 | x /= 10; 17 | } 18 | return minus ? (-res) : res; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /FirstMissingPositive/FirstMissingPositive.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int firstMissingPositive(int A[], int n) { 4 | int i = 0; 5 | while (i < n) { 6 | if (0 < A[i] && A[i] <= n && A[i] != A[A[i]-1]) { 7 | swap(A[i], A[A[i]-1]); 8 | } else { 9 | i++; 10 | } 11 | } 12 | for (int i = 0; i < n; i++) { 13 | if (A[i] != i + 1) { 14 | return i + 1; 15 | } 16 | } 17 | return n + 1; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /PalindromeNumber/PalindromeNumber.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPalindrome(int x) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | 7 | if (x < 0) return false; 8 | 9 | int base = 1; 10 | while (x / base >= 10) { 11 | base *= 10; 12 | } 13 | while (x) { 14 | if (x / base != x % 10) 15 | return false; 16 | x = (x % base) / 10; 17 | base /= 100; 18 | } 19 | return true; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Sqrt(x)/Sqrt(x).cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int sqrt(int x) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | long long lf = 0; 7 | long long rt = x; 8 | while (lf <= rt) { 9 | long long m = (lf + rt) >> 1; 10 | long long sq = m * m; 11 | if (sq == (long long)x) 12 | return m; 13 | else if (sq < (long long)x) 14 | lf = m + 1; 15 | else 16 | rt = m - 1; 17 | } 18 | return (int)rt; 19 | } 20 | }; -------------------------------------------------------------------------------- /UniquePaths/UniquePaths.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int uniquePaths(int m, int n) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | 7 | vector> dp(m, vector(n, 0)); 8 | for (int i = 0; i < m; i++) 9 | dp[i][0] = 1; 10 | for (int j = 0; j < n; j++) 11 | dp[0][j] = 1; 12 | for (int i = 1; i < m; i++) { 13 | for (int j = 1; j < n; j++) 14 | dp[i][j] = dp[i-1][j] + dp[i][j-1]; 15 | } 16 | return dp[m-1][n-1]; 17 | } 18 | }; -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | leetcode [![Total views](https://sourcegraph.com/api/repos/github.com/kedebug/leetcode/counters/views.png)](https://sourcegraph.com/github.com/kedebug/leetcode) 2 | ============ 3 | 4 | Solution set for LeetCode. 5 | 6 | 7 | 8 | The commit message of each problem stands for it's difficulty index, which means: 9 | - 1 Easy 10 | - 2 Normal 11 | - 3 Medium 12 | - 4 Hard 13 | - 5 Much Harder 14 | 15 | If you have found any method to optimize those solutions, please feel free to get in touch via kedebug0@gmail.com. 16 | 17 | LICENSE 18 | ============= 19 | No LICENSE, you can use it for any purpose. 20 | -------------------------------------------------------------------------------- /NextPermutation/NextPermutation.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void nextPermutation(vector &num) { 4 | int i = num.size() - 1; 5 | while (i >= 1 && num[i-1] >= num[i]) { 6 | i--; 7 | } 8 | if (i == 0) { 9 | reverse(num.begin(), num.end()); 10 | return; 11 | } 12 | for (int j = num.size() - 1; j >= i; j--) { 13 | if (num[j] > num[i-1]) { 14 | swap(num[j], num[i-1]); 15 | break; 16 | } 17 | } 18 | reverse(num.begin() + i, num.end()); 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /SearchInsertPosition/SearchInsertPosition.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int searchInsert(int A[], int n, int target) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | 7 | int low = 0, high = n - 1; 8 | while (low <= high) { 9 | int mid = low + (high - low) / 2; 10 | if (A[mid] == target) 11 | return mid; 12 | else if (A[mid] > target) 13 | high = mid - 1; 14 | else 15 | low = mid + 1; 16 | } 17 | return low; 18 | } 19 | }; -------------------------------------------------------------------------------- /JumpGame/JumpGame.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canJump(int A[], int n) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | 7 | int now = 0; 8 | int next = 0; 9 | while (now <= next) { 10 | next = max(next, now + A[now]); 11 | if (next >= n-1) 12 | return true; 13 | now += 1; 14 | } 15 | // for dynamic programming, we have below: 16 | // F[i] = max(F[i-1], A[i-1]) - 1; 17 | // if (F[i] < 0) return false; 18 | return false; 19 | } 20 | }; -------------------------------------------------------------------------------- /MergeSortedArray/MergeSortedArray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void merge(int A[], int m, int B[], int n) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | 7 | int end = m + n - 1; 8 | m -= 1; 9 | n -= 1; 10 | while (m >= 0 && n >= 0) { 11 | if (A[m] > B[n]) 12 | A[end--] = A[m--]; 13 | else 14 | A[end--] = B[n--]; 15 | } 16 | while (m >= 0) 17 | A[end--] = A[m--]; 18 | while (n >= 0) 19 | A[end--] = B[n--]; 20 | } 21 | }; -------------------------------------------------------------------------------- /LongestCommonPrefix/LongestCommonPrefix.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string longestCommonPrefix(vector &strs) { 4 | if (strs.empty()) { 5 | return string(); 6 | } 7 | for (int i = 0; i < strs[0].size(); i++) { 8 | for (int j = 1; j < strs.size(); j++) { 9 | if (i == strs[j].size()) { 10 | return strs[j]; 11 | } else if (i < strs[j].size() && strs[0][i] != strs[j][i]) { 12 | return strs[j].substr(0, i); 13 | } 14 | } 15 | } 16 | return strs[0]; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /MaximumDepthofBinaryTree/MaximumDepthofBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | int maxDepth(TreeNode *root) { 13 | // Start typing your C/C++ solution below 14 | // DO NOT write int main() function 15 | if (root == NULL) 16 | return 0; 17 | int lf = 1 + maxDepth(root->left); 18 | int rt = 1 + maxDepth(root->right); 19 | return max(lf, rt); 20 | } 21 | }; -------------------------------------------------------------------------------- /MaximumProductSubarray/MaximumProductSubarray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProduct(int A[], int n) { 4 | if (n == 0) { 5 | return 0; 6 | } 7 | int result = A[0]; 8 | int premax = A[0]; 9 | int premin = A[0]; 10 | for (int i = 1; i < n; i++) { 11 | int heremax = max(A[i], max(A[i] * premax, A[i] * premin)); 12 | int heremin = min(A[i], min(A[i] * premax, A[i] * premin)); 13 | result = max(result, heremax); 14 | premax = heremax; 15 | premin = heremin; 16 | } 17 | return result; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /RotateImage/RotateImage.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void rotate(vector>& matrix) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | 7 | int n = matrix.size(); 8 | for (int i = 0; i < n / 2; i++) { 9 | for (int j = i; j < n - 1 - i; j++) { 10 | int x = matrix[i][j]; 11 | matrix[i][j] = matrix[n-1-j][i]; 12 | matrix[n-1-j][i] = matrix[n-1-i][n-1-j]; 13 | matrix[n-1-i][n-1-j] = matrix[j][n-1-i]; 14 | matrix[j][n-1-i] = x; 15 | } 16 | } 17 | } 18 | }; -------------------------------------------------------------------------------- /N-QueensII/N-QueensII.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int totalNQueens(int n) { 4 | int result = 0; 5 | dfs(result, n, 0, 0, 0); 6 | return result; 7 | } 8 | 9 | void dfs(int& result, int n, int col, int l, int r) { 10 | int mask = (1 << n) - 1; 11 | if (col == mask) { 12 | result++; 13 | } else { 14 | int valid = mask & (~(col | l | r)); 15 | while (valid) { 16 | int p = valid & (-valid); 17 | valid -= p; 18 | dfs(result, n, col + p, (l + p) << 1, (r + p) >> 1); 19 | } 20 | } 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /JumpGameII/JumpGameII.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int jump(int A[], int n) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | 7 | int begin = 0, end = 0; 8 | int min_step = 0; 9 | int max_next = 0; 10 | 11 | while (end < n - 1) { 12 | min_step += 1; 13 | for (int i = begin; i <= end; i++) 14 | max_next = max(max_next, i + A[i]); 15 | if (max_next <= end) 16 | return -1; 17 | begin = end + 1; 18 | end = max_next; 19 | } 20 | return min_step; 21 | } 22 | }; -------------------------------------------------------------------------------- /LongestSubstringWithoutRepeatingCharacters/LongestSubstringWithoutRepeatingCharacters.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int lengthOfLongestSubstring(string s) { 4 | int hash[256]; 5 | for (int i = 0; i < 256; i++) { 6 | hash[i] = -1; 7 | } 8 | int maxlen = 0; 9 | int start = 0; 10 | for (int limit = 0; limit < s.size(); limit++) { 11 | if (hash[s[limit]] != -1) { 12 | start = max(start, hash[s[limit]] + 1); 13 | } 14 | maxlen = max(maxlen, limit - start + 1); 15 | hash[s[limit]] = limit; 16 | } 17 | return maxlen; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /Pascal'sTriangle/Pascal'sTriangle.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector > generate(int numRows) { 4 | vector> triangle; 5 | if (numRows == 0) { 6 | return triangle; 7 | } 8 | triangle.push_back(vector(1, 1)); 9 | for (int i = 1; i < numRows; i++) { 10 | vector& prev = triangle.back(); 11 | vector row(i + 1, 0); 12 | row[0] = row[i] = 1; 13 | for (int j = 0; j < i - 1; j++) { 14 | row[j+1] = prev[j] + prev[j+1]; 15 | } 16 | triangle.push_back(row); 17 | } 18 | return triangle; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /PlusOne/PlusOne.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector plusOne(vector& digits) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | 7 | int carry = 0; 8 | int size = digits.size(); 9 | digits[size-1] += 1; 10 | 11 | for (int i = size - 1; i >= 0; i--) { 12 | int val = digits[i]; 13 | digits[i] = (val + carry) % 10; 14 | carry = (val + carry) / 10; 15 | if (carry == 0) break; 16 | } 17 | if (carry) { 18 | digits.insert(digits.begin(), carry); 19 | } 20 | return digits; 21 | } 22 | }; -------------------------------------------------------------------------------- /ContainerWithMostWater/ContainerWithMostWater.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxArea(vector& height) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | if (height.size() < 2) 7 | return 0; 8 | int left = 0; 9 | int right = height.size() - 1; 10 | int maxarea = 0; 11 | while (left < right) { 12 | maxarea = max(maxarea, min(height[left], height[right]) * (right - left)); 13 | if (height[left] < height[right]) 14 | left += 1; 15 | else 16 | right -= 1; 17 | } 18 | return maxarea; 19 | } 20 | }; -------------------------------------------------------------------------------- /Anagrams/Anagrams.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector anagrams(vector &strs) { 4 | vector result; 5 | map exists; 6 | for (int i = 0; i < strs.size(); i++) { 7 | string u = strs[i]; 8 | sort(u.begin(), u.end()); 9 | if (exists.find(u) == exists.end()) { 10 | exists[u] = i; 11 | } else { 12 | if (exists[u] >= 0) { 13 | result.push_back(strs[exists[u]]); 14 | exists[u] = -1; 15 | } 16 | result.push_back(strs[i]); 17 | } 18 | } 19 | return result; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /DecodeWays/DecodeWays.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numDecodings(string s) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | 7 | if (s.empty()) return 0; 8 | 9 | vector dp(s.size() + 1, 0); 10 | dp[0] = 1; 11 | for (int i = 1; i <= s.size(); i++) { 12 | if (s[i-1] != '0') 13 | dp[i] = dp[i-1]; 14 | if (i > 1 && s[i-2] != '0') { 15 | int x = s[i-2] - '0'; 16 | x = 10 * x + s[i-1] - '0'; 17 | if (0 < x && x <= 26) 18 | dp[i] += dp[i-2]; 19 | } 20 | } 21 | return dp[s.size()]; 22 | } 23 | }; -------------------------------------------------------------------------------- /Pascal'sTriangleII/Pascal'sTriangleII.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector getRow(int rowIndex) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | 7 | vector row[2]; 8 | row[0].resize(rowIndex+1); 9 | row[1].resize(rowIndex+1); 10 | row[0][0] = 1; 11 | 12 | int T1 = 1, T2 = 0; 13 | for (int i = 1; i <= rowIndex; i++) { 14 | T1 ^= 1, T2 ^= 1; 15 | row[T2][0] = 1; 16 | for (int j = 1; j < i; j++) { 17 | row[T2][j] = row[T1][j-1] + row[T1][j]; 18 | } 19 | row[T2][i] = 1; 20 | } 21 | return move(row[T2]); 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Permutations/Permutations.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> permute(vector& num) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | 7 | vector> result; 8 | dfs(num, 0, result); 9 | return move(result); 10 | } 11 | 12 | void dfs(vector& num, int step, vector>& result) { 13 | if (step == num.size()) { 14 | result.push_back(num); 15 | return; 16 | } 17 | for (int i = step; i < num.size(); i++) { 18 | swap(num[step], num[i]); 19 | dfs(num, step + 1, result); 20 | swap(num[i], num[step]); 21 | } 22 | } 23 | }; -------------------------------------------------------------------------------- /ZigZagConversion/ZigZagConversion.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string convert(string s, int nRows) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | 7 | if (nRows == 1) return s; 8 | string result; 9 | if (s.size() == 0) return result; 10 | 11 | int delta = nRows*2-2; 12 | for (int i = 0; i < nRows; i++) { 13 | for (int j = i; j < s.size(); j += delta) { 14 | result += s[j]; 15 | if (i == 0 || i == nRows-1) continue; 16 | if (j + (nRows-i-1)*2 < s.size()) 17 | result += s[j+(nRows-i-1)*2]; 18 | } 19 | } 20 | return result; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /DistinctSubsequences/DistinctSubsequences.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numDistinct(string S, string T) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | 7 | int M = S.size(); 8 | int N = T.size(); 9 | 10 | if (M == 0 && N == 0) 11 | return 1; 12 | else if (M < N) 13 | return 0; 14 | 15 | int F[N+1]; 16 | memset(F, 0, sizeof(int)*(N+1)); 17 | F[0] = 1; 18 | for (int i = 1; i <= M; i++) { 19 | for (int j = N; j >= 1; j--) { 20 | if (S[i-1] == T[j-1]) 21 | F[j] = F[j-1] + F[j]; 22 | } 23 | } 24 | return F[N]; 25 | } 26 | }; -------------------------------------------------------------------------------- /RemoveDuplicatesfromSortedArrayII/RemoveDuplicatesfromSortedArrayII.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int removeDuplicates(int A[], int n) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | 7 | if (n == 0) return 0; 8 | 9 | int low = 0, high; 10 | int count = 1; 11 | for (high = 1; high < n; high++) { 12 | if (A[low] == A[high]) { 13 | if (count < 2) { 14 | count += 1; 15 | A[++low] = A[high]; 16 | } 17 | } 18 | else { 19 | A[++low] = A[high]; 20 | count = 1; 21 | } 22 | } 23 | return low + 1; 24 | } 25 | }; -------------------------------------------------------------------------------- /RemoveDuplicatesfromSortedList/RemoveDuplicatesfromSortedList.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode *deleteDuplicates(ListNode *head) { 12 | if (head == NULL) { 13 | return NULL; 14 | } 15 | ListNode* prev = head; 16 | ListNode* curr = head->next; 17 | while (curr) { 18 | if (prev->val != curr->val) { 19 | prev->next = curr; 20 | prev = prev->next; 21 | } 22 | curr = curr->next; 23 | } 24 | prev->next = NULL; 25 | return head; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /SameTree/SameTree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | bool isSameTree(TreeNode *p, TreeNode *q) { 13 | // Start typing your C/C++ solution below 14 | // DO NOT write int main() function 15 | if (p == NULL && q == NULL) 16 | return true; 17 | if (p == NULL || q == NULL) 18 | return false; 19 | if (p->val == q->val) { 20 | bool flag = isSameTree(p->left, q->left); 21 | if (!flag) return false; 22 | return isSameTree(p->right, q->right); 23 | } 24 | return false; 25 | } 26 | }; -------------------------------------------------------------------------------- /RomantoInteger/RomantoInteger.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int romanToInt(string s) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | int hash[256]; 7 | hash['I'] = 1; hash['V'] = 5; 8 | hash['X'] = 10; hash['L'] = 50; 9 | hash['C'] = 100; hash['D'] = 500; 10 | hash['M'] = 1000; 11 | 12 | int result = 0; 13 | int num = 0; 14 | for (size_t i = 0; i < s.size(); i++) { 15 | if (hash[s[i]] == num) { 16 | num += hash[s[i]]; 17 | } 18 | else if (hash[s[i]] > num) { 19 | if (num) { 20 | result += hash[s[i]] - num; 21 | num = 0; 22 | } 23 | else num = hash[s[i]]; 24 | } 25 | else { 26 | result += num; 27 | num = hash[s[i]]; 28 | } 29 | } 30 | if (num) result += num; 31 | return result; 32 | } 33 | }; -------------------------------------------------------------------------------- /MinimumDepthofBinaryTree/MinimumDepthofBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | int minDepth(TreeNode *root) { 13 | // Start typing your C/C++ solution below 14 | // DO NOT write int main() function 15 | if (root == NULL) 16 | return 0; 17 | if (root->left == NULL && root->right == NULL) 18 | return 1; 19 | int lf = INT_MAX, rt = INT_MAX; 20 | if (root->left) 21 | lf = 1 + minDepth(root->left); 22 | if (root->right) 23 | rt = 1 + minDepth(root->right); 24 | return min(lf, rt); 25 | } 26 | }; -------------------------------------------------------------------------------- /Subsets/Subsets.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector > subsets(vector& S) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | 7 | vector> result; 8 | vector subset; 9 | 10 | sort(S.begin(), S.end()); 11 | DFS(subset, 0, S, result); 12 | return move(result); 13 | } 14 | 15 | void DFS(vector& subset, int step, vector& S, vector>& result) { 16 | if (step == S.size()) { 17 | result.push_back(subset); 18 | return; 19 | } 20 | subset.push_back(S[step]); 21 | DFS(subset, step + 1, S, result); 22 | subset.pop_back(); 23 | 24 | DFS(subset, step + 1, S, result); 25 | } 26 | }; -------------------------------------------------------------------------------- /GrayCode/GrayCode.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector grayCode(int n) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | 7 | vector gray_code; 8 | for (int i = 0; i < (1 << n); i++) 9 | gray_code.push_back((i >> 1) ^ i); 10 | return gray_code; 11 | } 12 | }; 13 | 14 | // More comprehensible solution 15 | class Solution { 16 | public: 17 | vector grayCode(int n) { 18 | vector result(1, 0); 19 | for (int i = 0; i < n; i++) { 20 | int curr = result.size(); 21 | while (curr) { 22 | curr--; 23 | int x = result[curr]; 24 | result.push_back((1 << i) + x); 25 | } 26 | } 27 | return result; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /BalancedBinaryTree/BalancedBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | bool isBalanced(TreeNode *root) { 13 | // Start typing your C/C++ solution below 14 | // DO NOT write int main() function 15 | bool flag = true; 16 | dfs(root, flag); 17 | return flag; 18 | } 19 | int dfs(TreeNode* node, bool& flag) { 20 | if (node == NULL) 21 | return 0; 22 | int lf = 1 + dfs(node->left, flag); 23 | int rt = 1 + dfs(node->right, flag); 24 | 25 | if (abs(rt - lf) > 1) 26 | flag = false; 27 | return max(lf, rt); 28 | } 29 | }; -------------------------------------------------------------------------------- /CountandSay/CountandSay.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string countAndSay(int n) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | 7 | string begin = "1"; 8 | for (int i = 0; i < n - 1; i++) { 9 | string next; 10 | int start = 0; 11 | while (start < begin.size()) { 12 | int end = start; 13 | int count = 0; 14 | while (end < begin.size() && begin[start] == begin[end]) { 15 | end += 1; 16 | count += 1; 17 | } 18 | next += char('0' + count); 19 | next += begin[start]; 20 | start = end; 21 | } 22 | begin = next; 23 | } 24 | return begin; 25 | } 26 | }; -------------------------------------------------------------------------------- /Combinations/Combinations.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector > combine(int n, int k) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | 7 | vector> result; 8 | vector comb; 9 | DFS(comb, 0, 0, k, n, result); 10 | return move(result); 11 | } 12 | 13 | void DFS(vector& comb, int step, int p, int k, int n, vector>& result) { 14 | if (step == k) { 15 | result.push_back(comb); 16 | return; 17 | } 18 | if (n - p < k - step) 19 | return; 20 | 21 | comb.push_back(p + 1); 22 | DFS(comb, step + 1, p + 1, k, n, result); 23 | comb.pop_back(); 24 | 25 | DFS(comb, step, p + 1, k, n, result); 26 | } 27 | }; -------------------------------------------------------------------------------- /ValidParentheses/ValidParentheses.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isValid(string s) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | 7 | int n = s.size(); 8 | char stack[n]; 9 | int size = 0; 10 | int hash[256]; 11 | 12 | hash['('] = 0, hash['{'] = 1, hash['['] = 2; 13 | hash[')'] = 3, hash['}'] = 4, hash[']'] = 5; 14 | 15 | 16 | for (int i = 0; i < n; i++) { 17 | if (hash[s[i]] < 3) 18 | stack[size++] = s[i]; 19 | else { 20 | if (size == 0) return false; 21 | if ((hash[s[i]] % 3) != hash[stack[size-1]]) return false; 22 | size -= 1; 23 | } 24 | } 25 | return size ? false : true; 26 | } 27 | }; -------------------------------------------------------------------------------- /PopulatingNextRightPointersinEachNode/PopulatingNextRightPointersinEachNode.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree with next pointer. 3 | * struct TreeLinkNode { 4 | * int val; 5 | * TreeLinkNode *left, *right, *next; 6 | * TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | void connect(TreeLinkNode *root) { 12 | if (root == NULL) { 13 | return; 14 | } 15 | while (root->left) { 16 | TreeLinkNode* node = root; 17 | while (node) { 18 | node->left->next = node->right; 19 | if (node->next) { 20 | node->right->next = node->next->left; 21 | } 22 | node = node->next; 23 | } 24 | root = root->left; 25 | } 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /EditDistance/EditDistance.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minDistance(string word1, string word2) { 4 | vector> dp(word1.size() + 1, vector(word2.size() + 1, 0)); 5 | for (int i = 1; i <= word1.size(); i++) { 6 | dp[i][0] = i; 7 | } 8 | for (int j = 1; j <= word2.size(); j++) { 9 | dp[0][j] = j; 10 | } 11 | for (int i = 1; i <= word1.size(); i++) { 12 | for (int j = 1; j <= word2.size(); j++) { 13 | if (word1[i-1] == word2[j-1]) { 14 | dp[i][j] = dp[i-1][j-1]; 15 | } else { 16 | dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + 1; 17 | dp[i][j] = min(dp[i][j], dp[i-1][j-1] + 1); 18 | } 19 | } 20 | } 21 | return dp[word1.size()][word2.size()]; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /ValidSudoku/ValidSudoku.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isValidSudoku(vector> &board) { 4 | vector> rows(9, vector(9, false)); 5 | vector> cols(9, vector(9, false)); 6 | vector> cells(9, vector(9, false)); 7 | 8 | for (int i = 0; i < 9; i++) { 9 | for (int j = 0; j < 9; j++) { 10 | if (board[i][j] != '.') { 11 | int x = board[i][j] - '1'; 12 | if (rows[i][x] || cols[j][x] || cells[(j/3)*3+i/3][x]) { 13 | return false; 14 | } 15 | rows[i][x] = true; 16 | cols[j][x] = true; 17 | cells[(j/3)*3+i/3][x] = true; 18 | } 19 | } 20 | } 21 | return true; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /PalindromePartitioningII/PalindromePartitioningII.cpp: -------------------------------------------------------------------------------- 1 | const int MAXN = 2010; 2 | const int INFS = 0x3fffffff; 3 | 4 | class Solution { 5 | public: 6 | int minCut(string s) { 7 | // Start typing your C/C++ solution below 8 | // DO NOT write int main() function 9 | 10 | int n = s.size(); 11 | memset(dp, false, sizeof(dp)); 12 | for (int i = 0; i < n; i++) 13 | dp[i+1][i] = dp[i][i] = true; 14 | for (int d = 1; d < n; d++) 15 | for (int i = 0, j = i+d; j < n; i++, j++) 16 | if (s[i] == s[j]) 17 | dp[i][j] |= dp[i+1][j-1]; 18 | for (int i = 0; i < n; i++) 19 | F[i] = INFS; 20 | F[0] = 0; 21 | for (int i = 1; i < n; i++) 22 | for (int j = 0; j < i; j++) 23 | if (dp[0][i]) 24 | F[i] = 0; 25 | else if (dp[j+1][i]) 26 | F[i] = min(F[i], F[j] + 1); 27 | return F[n-1]; 28 | 29 | } 30 | private: 31 | bool dp[MAXN][MAXN]; 32 | int F[MAXN]; 33 | }; 34 | -------------------------------------------------------------------------------- /SearchinRotatedSortedArray/SearchinRotatedSortedArray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int search(int A[], int n, int target) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | 7 | int lf = 0, rt = n - 1; 8 | while (lf <= rt) { 9 | int m = lf + (rt - lf) / 2; 10 | if (A[m] == target) 11 | return m; 12 | 13 | if (A[lf] <= A[m]) { 14 | if (A[lf] <= target && target < A[m]) 15 | rt = m - 1; 16 | else 17 | lf = m + 1; 18 | } 19 | else { 20 | if (A[m] < target && target <= A[rt]) 21 | lf = m + 1; 22 | else 23 | rt = m - 1; 24 | } 25 | } 26 | return -1; 27 | } 28 | }; -------------------------------------------------------------------------------- /BestTimetoBuyandSellStockIII/BestTimetoBuyandSellStockIII.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(vector &prices) { 4 | if (prices.size() < 2) { 5 | return 0; 6 | } 7 | int n = prices.size(); 8 | vector dp1(n, 0); 9 | vector dp2(n, 0); 10 | int minval = prices[0]; 11 | for (int i = 1; i < n; i++) { 12 | minval = min(minval, prices[i]); 13 | dp1[i] = max(dp1[i-1], prices[i] - minval); 14 | } 15 | int maxval = prices[n-1]; 16 | for (int i = n - 2; i >= 0; i--) { 17 | maxval = max(maxval, prices[i]); 18 | dp2[i] = max(dp2[i+1], maxval - prices[i]); 19 | } 20 | int result = 0; 21 | for (int i = 0; i < n; i++) { 22 | result = max(result, dp1[i] + dp2[i]); 23 | } 24 | return result; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /GenerateParentheses/GenerateParentheses.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector generateParenthesis(int n) { 4 | vector result; 5 | string s; 6 | if (n == 0) { 7 | return result; 8 | } 9 | dfs(result, s, n, n); 10 | return result; 11 | } 12 | void dfs(vector& result, string& s, int left, int right) { 13 | if (left > right) { 14 | return; 15 | } 16 | if (left == 0 && right == 0) { 17 | result.push_back(s); 18 | return; 19 | } 20 | if (left >= 1) { 21 | s.push_back('('); 22 | dfs(result, s, left - 1, right); 23 | s.pop_back(); 24 | } 25 | if (right >= 1) { 26 | s.push_back(')'); 27 | dfs(result, s, left, right - 1); 28 | s.pop_back(); 29 | } 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /ConvertSortedArraytoBinarySearchTree/ConvertSortedArraytoBinarySearchTree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | TreeNode *sortedArrayToBST(vector &num) { 13 | return dfs(num, 0, num.size() - 1); 14 | } 15 | TreeNode* dfs(vector& num, int start, int limit) { 16 | if (start > limit) { 17 | return NULL; 18 | } 19 | if (start == limit) { 20 | return new TreeNode(num[start]); 21 | } 22 | int middle = (start + limit) / 2; 23 | TreeNode* root = new TreeNode(num[middle]); 24 | root->left = dfs(num, start, middle - 1); 25 | root->right = dfs(num, middle + 1, limit); 26 | return root; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /3SumClosest/3SumClosest.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int threeSumClosest(vector &num, int target) { 4 | sort(num.begin(), num.end()); 5 | int delta = INT_MAX; 6 | int closest = 0; 7 | for (int i = 0; i < num.size(); i++) { 8 | int start = i + 1; 9 | int limit = num.size() - 1; 10 | while (start < limit) { 11 | int sum = num[i] + num[start] + num[limit]; 12 | if (abs(sum - target) < delta) { 13 | delta = abs(sum - target); 14 | closest = sum; 15 | } 16 | if (sum == target) { 17 | return target; 18 | } else if (sum < target) { 19 | start++; 20 | } else { 21 | limit--; 22 | } 23 | } 24 | } 25 | return closest; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /DivideTwoIntegers/DivideTwoIntegers.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int divide(int dividend, int divisor) { 4 | long long int divid = dividend; 5 | long long int divis = divisor; 6 | bool neg = false; 7 | if (divid < 0) { 8 | neg = neg ? false : true; 9 | divid = -divid; 10 | } 11 | if (divis < 0) { 12 | neg = neg ? false : true; 13 | divis = -divis; 14 | } 15 | long long int result = 0; 16 | while (divid >= divis) { 17 | long long int x = divis; 18 | int shift = 0; 19 | while ((x << 1) <= divid) { 20 | x <<= 1; 21 | shift += 1; 22 | } 23 | result += 1 << shift; 24 | divid -= x; 25 | } 26 | if (neg) { 27 | result = -result; 28 | } 29 | return result; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /RegularExpressionMatching/RegularExpressionMatching.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isMatch(const char *s, const char *p) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | 7 | if (s == NULL || p == NULL) 8 | return false; 9 | if (*p == '\0') 10 | return *s == '\0'; 11 | 12 | if (*(p+1) == '*') { 13 | // 14 | // notice: ".*" means repeat '.' 0 or more times 15 | // 16 | while ((*s != '\0' && *p == '.') || *s == *p) { 17 | if (isMatch(s, p + 2)) 18 | return true; 19 | s += 1; 20 | } 21 | return isMatch(s, p + 2); 22 | } 23 | else if ((*s != '\0' && *p == '.') || *s == *p) { 24 | return isMatch(s + 1, p + 1); 25 | } 26 | return false; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /LongestPalindromicSubstring/LongestPalindromicSubstring.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string longestPalindrome(string s) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | 7 | int beg = 0, end = 0; 8 | int longest = 1; 9 | 10 | for (int i = 0; i < s.size(); i++) { 11 | dp[i][i] = dp[i+1][i] = true; 12 | } 13 | for (int d = 1; d < s.size(); d++) { 14 | for (int i = 0, j = i + d; j < s.size(); i++, j++) { 15 | dp[i][j] = false; 16 | if (s[i] == s[j]) dp[i][j] |= dp[i+1][j-1]; 17 | if (dp[i][j] && longest < j-i+1) { 18 | beg = i, end = j; 19 | } 20 | } 21 | } 22 | return s.substr(beg, end - beg + 1); 23 | } 24 | private: 25 | static const int MAXN = 1010; 26 | bool dp[MAXN][MAXN]; 27 | }; 28 | -------------------------------------------------------------------------------- /AddBinary/AddBinary.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string addBinary(string a, string b) { 4 | string c; 5 | reverse(a.begin(), a.end()); 6 | reverse(b.begin(), b.end()); 7 | int carry = 0; 8 | int i = 0; 9 | while (i < a.size() && i < b.size()) { 10 | carry += a[i] - '0' + b[i] - '0'; 11 | c += carry % 2 + '0'; 12 | carry /= 2; 13 | i++; 14 | } 15 | while (i < a.size()) { 16 | carry += a[i] - '0'; 17 | c += carry % 2 + '0'; 18 | carry /= 2; 19 | i++; 20 | } 21 | while (i < b.size()) { 22 | carry += b[i] - '0'; 23 | c += carry % 2 + '0'; 24 | carry /= 2; 25 | i++; 26 | } 27 | while (carry) { 28 | c += carry % 2 + '0'; 29 | carry /= 2; 30 | } 31 | reverse(c.begin(), c.end()); 32 | return c; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /ClimbingStairs/ClimbingStairs.cpp: -------------------------------------------------------------------------------- 1 | 2 | 3 | class Matrix { 4 | public: 5 | int x00, x01; 6 | int x10, x11; 7 | Matrix() {} 8 | Matrix(int _x00, int _x01, int _x10, int _x11) 9 | : x00(_x00), x01(_x01), x10(_x10), x11(_x11) {} 10 | Matrix operator * (const Matrix& o) { 11 | Matrix m; 12 | m.x00 = x00 * o.x00 + x01 * o.x10; 13 | m.x01 = x00 * o.x01 + x01 * o.x11; 14 | m.x10 = x10 * o.x00 + x11 * o.x10; 15 | m.x11 = x10 * o.x01 + x11 * o.x11; 16 | return m; 17 | } 18 | }; 19 | 20 | class Solution { 21 | public: 22 | int climbStairs(int n) { 23 | // Start typing your C/C++ solution below 24 | // DO NOT write int main() function 25 | if (n <= 1) return 1; 26 | Matrix m(1, 1, 1, 0); 27 | Matrix e(1, 0, 1, 0); 28 | while (n) { 29 | if (n & 1) 30 | e = e * m; 31 | m = m * m; 32 | n /= 2; 33 | } 34 | return e.x10; 35 | } 36 | }; -------------------------------------------------------------------------------- /RemoveDuplicatesfromSortedListII/RemoveDuplicatesfromSortedListII.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode *deleteDuplicates(ListNode *head) { 12 | ListNode prevhead(0); 13 | ListNode* prev = &prevhead; 14 | ListNode* curr = head; 15 | while (curr) { 16 | if (curr->next && curr->val == curr->next->val) { 17 | ListNode* next = curr->next; 18 | while (next && next->val == curr->val) { 19 | next = next->next; 20 | } 21 | curr = next; 22 | } else { 23 | prev->next = curr; 24 | prev = prev->next; 25 | curr = curr->next; 26 | } 27 | } 28 | prev->next = NULL; 29 | return prevhead.next; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /ImplementstrStr/ImplementstrStr.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | char *strStr(char *haystack, char *needle) { 4 | int n = strlen(haystack); 5 | int m = strlen(needle); 6 | if (m == 0) { 7 | return haystack; 8 | } 9 | vector next(m, -1); 10 | for (int i = 1, j = -1; i < m; i++) { 11 | while (j != -1 && needle[j+1] != needle[i]) { 12 | j = next[j]; 13 | } 14 | if (needle[j+1] == needle[i]) { 15 | j++; 16 | } 17 | next[i] = j; 18 | } 19 | for (int i = 0, j = -1; i < n; i++) { 20 | while (j != -1 && needle[j+1] != haystack[i]) { 21 | j = next[j]; 22 | } 23 | if (needle[j+1] == haystack[i]) { 24 | j++; 25 | } 26 | if (j == m - 1) { 27 | return haystack + i - m + 1; 28 | } 29 | } 30 | return NULL; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /RemoveNthNodeFromEndofList/RemoveNthNodeFromEndofList.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode *removeNthFromEnd(ListNode *head, int n) { 12 | // Start typing your C/C++ solution below 13 | // DO NOT write int main() function 14 | 15 | ListNode prevHead(0); 16 | prevHead.next = head; 17 | 18 | ListNode *prev = &prevHead; 19 | ListNode *slow = head; 20 | ListNode *fast = head; 21 | 22 | for (int i = 0; i < n; i++) 23 | fast = fast->next; 24 | 25 | while (fast != NULL) { 26 | prev = prev->next; 27 | slow = slow->next; 28 | fast = fast->next; 29 | } 30 | 31 | prev->next = slow->next; 32 | delete slow; 33 | return prevHead.next; 34 | } 35 | }; -------------------------------------------------------------------------------- /SymmetricTree/SymmetricTree_recursively.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | bool isSymmetric(TreeNode *root) { 13 | // Start typing your C/C++ solution below 14 | // DO NOT write int main() function 15 | if (root == NULL) 16 | return true; 17 | return dfs(root->left, root->right); 18 | 19 | } 20 | bool dfs(TreeNode *lhs, TreeNode *rhs) { 21 | if (lhs == NULL && rhs == NULL) 22 | return true; 23 | if (lhs == NULL || rhs == NULL) 24 | return false; 25 | 26 | if (lhs->val == rhs->val) { 27 | bool flag = dfs(lhs->left, rhs->right); 28 | if (!flag) return false; 29 | return dfs(lhs->right, rhs->left); 30 | } 31 | return false; 32 | } 33 | }; -------------------------------------------------------------------------------- /ValidPalindrome/ValidPalindrome.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPalindrome(string s) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | 7 | string alphas; 8 | 9 | for (size_t i = 0; i < s.size(); i++) { 10 | if ('A' <= s[i] && s[i] <= 'Z') 11 | alphas += s[i] - 'A' + 'a'; 12 | else if ('a' <= s[i] && s[i] <= 'z') 13 | alphas += s[i]; 14 | else if ('0' <= s[i] && s[i] <= '9') 15 | alphas += s[i]; 16 | } 17 | 18 | if (alphas.size() == 0) 19 | return true; 20 | 21 | size_t beg = 0, end = alphas.size() - 1; 22 | 23 | while (beg < end) { 24 | if (alphas[beg] == alphas[end]) { 25 | beg += 1; 26 | end -= 1; 27 | } else { 28 | return false; 29 | } 30 | } 31 | return true; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /SwapNodesinPairs/SwapNodesinPairs.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode *swapPairs(ListNode *head) { 12 | // Start typing your C/C++ solution below 13 | // DO NOT write int main() function 14 | 15 | if (head == NULL) return NULL; 16 | 17 | ListNode prevHead(0); 18 | prevHead.next = head; 19 | ListNode *prev = &prevHead; 20 | ListNode *left = head; 21 | ListNode *right = head->next; 22 | 23 | while (left && right) { 24 | prev->next = right; 25 | left->next = right->next; 26 | right->next = left; 27 | 28 | prev = left; 29 | left = left->next; 30 | if (left) right = left->next; 31 | else right = NULL; 32 | } 33 | return prevHead.next; 34 | } 35 | }; -------------------------------------------------------------------------------- /SumRoottoLeafNumbers/SumRoottoLeafNumbers.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | int sumNumbers(TreeNode *root) { 13 | // Start typing your C/C++ solution below 14 | // DO NOT write int main() function 15 | int sum = 0; 16 | dfs(root, 0, sum); 17 | return sum; 18 | 19 | } 20 | void dfs(TreeNode *node, int val, int& sum) { 21 | if (node == NULL) return; 22 | 23 | val *= 10; 24 | val += node->val; 25 | 26 | if (node->left == NULL && node->right == NULL) { 27 | sum += val; 28 | return; 29 | } 30 | 31 | if (node->left) { 32 | dfs(node->left, val, sum); 33 | } 34 | if (node->right) { 35 | dfs(node->right, val, sum); 36 | } 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /StringtoInteger(atoi)/StringtoInteger(atoi).cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int atoi(const char *str) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | 7 | if (str == NULL) 8 | return 0; 9 | while (*str == ' ') { 10 | str++; 11 | } 12 | bool minus = false; 13 | if (*str == '+') { 14 | str++; 15 | } else if (*str == '-') { 16 | str++; 17 | minus = true; 18 | } 19 | long long int value = 0; 20 | for (; *str != '\0'; str++) { 21 | if ('0' <= *str && *str <= '9') { 22 | value *= 10; 23 | value += *str - '0'; 24 | } else { 25 | break; 26 | } 27 | } 28 | if (minus) 29 | value = -value; 30 | if (value > INT_MAX) 31 | value = INT_MAX; 32 | if (value < INT_MIN) 33 | value = INT_MIN; 34 | return (int)value; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /PermutationSequence/PermutationSequence.cpp: -------------------------------------------------------------------------------- 1 | 2 | const int factorial[10] = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880}; 3 | 4 | class Solution { 5 | public: 6 | string getPermutation(int n, int k) { 7 | // Start typing your C/C++ solution below 8 | // DO NOT write int main() function 9 | 10 | // 11 | // http://zh.wikipedia.org/wiki/%E5%BA%B7%E6%89%98%E5%B1%95%E5%BC%80 12 | // 13 | string sequence; 14 | bool hash[12]; 15 | memset(hash, false, sizeof(hash)); 16 | k -= 1; 17 | for (int i = n; i >= 1; i--) { 18 | int x = k / factorial[i-1]; 19 | int count = 0; 20 | for (int j = 1; j <= n; j++) { 21 | if (!hash[j]) count += 1; 22 | if (count == x + 1) { 23 | x = j; 24 | break; 25 | } 26 | } 27 | k %= factorial[i-1]; 28 | hash[x] = true; 29 | sequence += x + '0'; 30 | } 31 | return sequence; 32 | } 33 | }; -------------------------------------------------------------------------------- /ReverseLinkedListII/ReverseLinkedListII.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode *reverseBetween(ListNode *head, int m, int n) { 12 | // Start typing your C/C++ solution below 13 | // DO NOT write int main() function 14 | 15 | ListNode prev_head(0); 16 | prev_head.next = head; 17 | ListNode *prev = &prev_head; 18 | ListNode *current = head; 19 | 20 | for (int i = 0; i < m - 1; i++) { 21 | prev = prev->next; 22 | current = current->next; 23 | } 24 | ListNode *end = current; 25 | for (int i = m - 1; i < n; i++) { 26 | ListNode *next = current->next; 27 | current->next = prev->next; 28 | prev->next = current; 29 | current = next; 30 | } 31 | end->next = current; 32 | return prev_head.next; 33 | } 34 | }; -------------------------------------------------------------------------------- /PathSum/PathSum.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | bool hasPathSum(TreeNode *root, int sum) { 13 | // Start typing your C/C++ solution below 14 | // DO NOT write int main() function 15 | if (root == NULL) 16 | return false; 17 | return dfs(root, 0, sum); 18 | 19 | } 20 | 21 | bool dfs(TreeNode *node, int value, int target) { 22 | if (node->left == NULL && node->right == NULL) { 23 | if (value + node->val == target) 24 | return true; 25 | else 26 | return false; 27 | } 28 | bool flag = false; 29 | if (node->left) 30 | flag = dfs(node->left, node->val + value, target); 31 | if (flag) return true; 32 | if (node->right) 33 | return dfs(node->right, node->val + value, target); 34 | } 35 | }; -------------------------------------------------------------------------------- /UniquePathsII/UniquePathsII.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int uniquePathsWithObstacles(vector>& obstacleGrid) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | 7 | int m = obstacleGrid.size(); 8 | if (m == 0) return 0; 9 | int n = obstacleGrid[0].size(); 10 | 11 | vector> dp(m, vector(n, 0)); 12 | 13 | for (int i = 0; i < m; i++) { 14 | if (obstacleGrid[i][0] == 0) 15 | dp[i][0] = 1; 16 | else 17 | break; 18 | } 19 | for (int j = 0; j < n; j++) { 20 | if (obstacleGrid[0][j] == 0) 21 | dp[0][j] = 1; 22 | else 23 | break; 24 | } 25 | for (int i = 1; i < m; i++) { 26 | for (int j = 1; j < n; j++) { 27 | if (obstacleGrid[i][j] == 0) 28 | dp[i][j] = dp[i-1][j] + dp[i][j-1]; 29 | } 30 | } 31 | return dp[m-1][n-1]; 32 | 33 | } 34 | }; -------------------------------------------------------------------------------- /BinaryTreeMaximumPathSum/BinaryTreeMaximumPathSum.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | int maxPathSum(TreeNode *root) { 13 | if (root == NULL) { 14 | return 0; 15 | } 16 | int maxsum = INT_MIN; 17 | dfs(root, &maxsum); 18 | return maxsum; 19 | } 20 | 21 | int dfs(TreeNode* node, int* maxsum) { 22 | if (node == NULL) { 23 | return 0; 24 | } 25 | int left = dfs(node->left, maxsum); 26 | int right = dfs(node->right, maxsum); 27 | int val = node->val; 28 | if (max(left, right) > 0) { 29 | val += max(left, right); 30 | } 31 | int sum = node->val; 32 | if (left > 0) { 33 | sum += left; 34 | } 35 | if (right > 0) { 36 | sum += right; 37 | } 38 | *maxsum = max(*maxsum, sum); 39 | return val; 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /CloneGraph/CloneGraph.cc: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for undirected graph. 3 | * struct UndirectedGraphNode { 4 | * int label; 5 | * vector neighbors; 6 | * UndirectedGraphNode(int x) : label(x) {}; 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | UndirectedGraphNode* clone(UndirectedGraphNode* node, map& graph) { 12 | if (node == NULL) { 13 | return NULL; 14 | } 15 | if (graph.find(node) != graph.end()) { 16 | return graph[node]; 17 | } 18 | UndirectedGraphNode* newnode = new UndirectedGraphNode(node->label); 19 | graph[node] = newnode; 20 | for (int i = 0; i < node->neighbors.size(); i++) { 21 | UndirectedGraphNode* next = clone(node->neighbors[i], graph); 22 | newnode->neighbors.push_back(next); 23 | } 24 | return newnode; 25 | } 26 | 27 | UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) { 28 | map graph; 29 | return clone(node, graph); 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /MergeIntervals/MergeIntervals.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for an interval. 3 | * struct Interval { 4 | * int start; 5 | * int end; 6 | * Interval() : start(0), end(0) {} 7 | * Interval(int s, int e) : start(s), end(e) {} 8 | * }; 9 | */ 10 | 11 | inline bool operator < (const Interval& x, const Interval& y) { 12 | if (x.start == y.start) { 13 | return x.end < y.end; 14 | } 15 | return x.start < y.start; 16 | } 17 | 18 | class Solution { 19 | public: 20 | vector merge(vector &intervals) { 21 | vector result; 22 | if (intervals.empty()) { 23 | return result; 24 | } 25 | sort(intervals.begin(), intervals.end()); 26 | result.push_back(intervals[0]); 27 | for (int i = 1; i < intervals.size(); i++) { 28 | Interval& back = result.back(); 29 | if (back.end >= intervals[i].start) { 30 | back.end = max(back.end, intervals[i].end); 31 | } else { 32 | result.push_back(intervals[i]); 33 | } 34 | } 35 | return result; 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /SimplifyPath/SimplifyPath.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string simplifyPath(string path) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | 7 | vector path_stack; 8 | int i = 0; 9 | while (i < path.size()) { 10 | while (i < path.size() && path[i] == '/') i += 1; 11 | if (i == path.size()) break; 12 | string directory; 13 | while (i < path.size() && path[i] != '/') { 14 | directory += path[i]; 15 | i += 1; 16 | } 17 | if (directory == "..") { 18 | if (!path_stack.empty()) 19 | path_stack.pop_back(); 20 | } 21 | else if (directory != ".") { 22 | path_stack.push_back(directory); 23 | } 24 | } 25 | if (path_stack.empty()) 26 | return "/"; 27 | string simplified_path; 28 | for (int i = 0; i < path_stack.size(); i++) 29 | simplified_path += "/" + path_stack[i]; 30 | return simplified_path; 31 | } 32 | }; -------------------------------------------------------------------------------- /SearchinRotatedSortedArrayII/SearchinRotatedSortedArrayII.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool search(int A[], int n, int target) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | 7 | int lf = 0, rt = n - 1; 8 | while (lf <= rt) { 9 | int m = lf + (rt - lf) / 2; 10 | if (A[m] == target) 11 | return true; 12 | 13 | if (A[lf] < A[m]) { 14 | if (A[lf] <= target && target < A[m]) 15 | rt = m - 1; 16 | else 17 | lf = m + 1; 18 | } 19 | else if (A[lf] > A[m]) { 20 | if (A[m] < target && target <= A[rt]) 21 | lf = m + 1; 22 | else 23 | rt = m - 1; 24 | } 25 | else { 26 | bool onleft = search(A + lf + 1, m - lf - 1, target); 27 | if (onleft) return true; 28 | return search(A + m + 1, rt - m, target); 29 | } 30 | 31 | } 32 | return false; 33 | } 34 | }; -------------------------------------------------------------------------------- /SymmetricTree/SymmetricTree_iteratively.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | bool isSymmetric(TreeNode *root) { 13 | // Start typing your C/C++ solution below 14 | // DO NOT write int main() function 15 | if (root == NULL) 16 | return true; 17 | queue lhs, rhs; 18 | lhs.push(root->left); 19 | rhs.push(root->right); 20 | while (!lhs.empty() && !rhs.empty()) { 21 | TreeNode *l = lhs.front(); lhs.pop(); 22 | TreeNode *r = rhs.front(); rhs.pop(); 23 | if (l == NULL && r == NULL) continue; 24 | if (l == NULL || r == NULL) return false; 25 | if (l->val != r->val) return false; 26 | lhs.push(l->left); lhs.push(l->right); 27 | rhs.push(r->right); rhs.push(r->left); 28 | } 29 | if (lhs.empty() && rhs.empty()) 30 | return true; 31 | else 32 | return false; 33 | } 34 | }; -------------------------------------------------------------------------------- /LetterCombinationsofaPhoneNumber/LetterCombinationsofaPhoneNumber.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector letterCombinations(string digits) { 4 | map keypad; 5 | keypad[2] = string("abc"); 6 | keypad[3] = string("def"); 7 | keypad[4] = string("ghi"); 8 | keypad[5] = string("jkl"); 9 | keypad[6] = string("mno"); 10 | keypad[7] = string("pqrs"); 11 | keypad[8] = string("tuv"); 12 | keypad[9] = string("wxyz"); 13 | 14 | vector result; 15 | string letter; 16 | dfs(result, letter, digits, 0, keypad); 17 | return result; 18 | } 19 | void dfs(vector& result, string& letter, string& digits, int pos, map& keypad) { 20 | if (pos == digits.size()) { 21 | result.push_back(letter); 22 | return; 23 | } 24 | int x = digits[pos] - '0'; 25 | string s = keypad[x]; 26 | for (int i = 0; i < s.size(); i++) { 27 | letter.push_back(s[i]); 28 | dfs(result, letter, digits, pos + 1, keypad); 29 | letter.pop_back(); 30 | } 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /SubsetsII/SubsetsII.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> subsetsWithDup(vector& S) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | 7 | 8 | vector> subsets; 9 | vector integers; 10 | 11 | if (S.empty()) return subsets; 12 | 13 | sort(S.begin(), S.end()); 14 | DFS(integers, 0, S, subsets); 15 | 16 | return move(subsets); 17 | } 18 | 19 | void DFS(vector& integers, int start, vector& S, vector>& subsets) { 20 | if (start == S.size()) { 21 | subsets.push_back(integers); 22 | return; 23 | } 24 | int end = start; 25 | while (end + 1 < S.size() && S[start] == S[end+1]) 26 | end += 1; 27 | 28 | DFS(integers, end + 1, S, subsets); 29 | 30 | for (int i = start; i <= end; i++) { 31 | integers.push_back(S[i]); 32 | DFS(integers, end + 1, S, subsets); 33 | } 34 | for (int i = start; i <= end; i++) 35 | integers.pop_back(); 36 | } 37 | }; -------------------------------------------------------------------------------- /BinaryTreePreorderTraversal/BinaryTreePreorderTraversal.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | vector preorderTraversal(TreeNode *root) { 13 | vector result; 14 | TreeNode* node = root; 15 | while (node) { 16 | if (node->left == NULL) { 17 | result.push_back(node->val); 18 | node = node->right; 19 | } else { 20 | TreeNode* next = node->left; 21 | while (next->right && next->right != node) { 22 | next = next->right; 23 | } 24 | if (next->right == NULL) { 25 | next->right = node; 26 | result.push_back(node->val); 27 | node = node->left; 28 | } else { 29 | next->right = NULL; 30 | node = node->right; 31 | } 32 | } 33 | } 34 | return result; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /RestoreIPAddresses/RestoreIPAddresses.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector restoreIpAddresses(string s) { 4 | vector result; 5 | vector sk; 6 | dfs(result, sk, s, 0, 0); 7 | return result; 8 | } 9 | 10 | void dfs(vector& result, vector& sk, const string& s, int val, int pos) { 11 | if (sk.size() > 4) { 12 | return; 13 | } 14 | 15 | if (pos == s.size()) { 16 | if (sk.size() < 4 || val != 0) { 17 | return; 18 | } 19 | string ip; 20 | ip += to_string(sk[0]); 21 | for (int i = 1; i < 4; i++) { 22 | ip += "."; 23 | ip += to_string(sk[i]); 24 | } 25 | result.push_back(ip); 26 | return; 27 | } 28 | 29 | val = val * 10 + s[pos] - '0'; 30 | if (val > 255) { 31 | return; 32 | } 33 | if (val != 0) { 34 | dfs(result, sk, s, val, pos + 1); 35 | } 36 | sk.push_back(val); 37 | dfs(result, sk, s, 0, pos + 1); 38 | sk.pop_back(); 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /TwoSum/TwoSum.cpp: -------------------------------------------------------------------------------- 1 | bool lessthan(const pair& lhs, const pair& rhs) { 2 | if (lhs.first == rhs.first) 3 | return lhs.second < rhs.second; 4 | return lhs.first < rhs.first; 5 | } 6 | 7 | class Solution { 8 | public: 9 | vector twoSum(vector &numbers, int target) { 10 | // Start typing your C/C++ solution below 11 | // DO NOT write int main() function 12 | 13 | vector> vnum; 14 | for (size_t i = 0; i < numbers.size(); i++) { 15 | vnum.push_back(make_pair(numbers[i], i + 1)); 16 | } 17 | sort(vnum.begin(), vnum.end(), lessthan); 18 | vector ans; 19 | int s = 0, e = vnum.size() - 1; 20 | while (s < e) { 21 | if (vnum[s].first + vnum[e].first == target) { 22 | ans.push_back(min(vnum[s].second, vnum[e].second)); 23 | ans.push_back(max(vnum[s].second, vnum[e].second)); 24 | break; 25 | } 26 | else if (vnum[s].first + vnum[e].first > target) 27 | e -= 1; 28 | else 29 | s += 1; 30 | } 31 | return ans; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /SortColors/SortColors.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void sortColors(int A[], int n) { 4 | int p0 = -1; 5 | int p1 = 0; 6 | int p2 = n; 7 | while (p1 < p2) { 8 | if (A[p1] == 1) { 9 | p1++; 10 | } else if (A[p1] == 0) { 11 | swap(A[p0+1], A[p1]); 12 | p0++; 13 | p1++; 14 | } else { 15 | swap(A[p1], A[p2-1]); 16 | p2--; 17 | } 18 | } 19 | } 20 | }; 21 | 22 | // 23 | // Solution2 using the method like quicksort 24 | // 25 | class Solution2 { 26 | public: 27 | void sortColors(int A[], int n) { 28 | // Start typing your C/C++ solution below 29 | // DO NOT write int main() function 30 | 31 | int p = split(A, 0, n - 1, 0); 32 | split(A, p + 1, n - 1, 1); 33 | } 34 | int split(int A[], int low, int high, int pivot) { 35 | int i = low - 1; 36 | for (int j = low; j <= high; j++) { 37 | if (A[j] <= pivot) { 38 | i += 1; 39 | if (i != j) swap(A[i], A[j]); 40 | } 41 | } 42 | return i; 43 | } 44 | }; 45 | -------------------------------------------------------------------------------- /IntegertoRoman/IntegertoRoman.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string intToRoman(int num) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | char symbol[] = {'I', 'V', 'X', 'L','C', 'D', 'M'}; 7 | string result; 8 | int base = 1000; 9 | int d = 6; 10 | while (num) { 11 | int digit = num / base; 12 | appendRoman(digit, result, symbol + d); 13 | d -= 2; 14 | num %= base; 15 | base /= 10; 16 | } 17 | return result; 18 | } 19 | 20 | void appendRoman(int n, string& s, char symbol[]) { 21 | assert(n <= 9); 22 | 23 | if (n == 0) return; 24 | if (n <= 3) { 25 | s.append(n, symbol[0]); 26 | } 27 | else if (n == 4) { 28 | s.append(1, symbol[0]); 29 | s.append(1, symbol[1]); 30 | } 31 | else if (n <= 8) { 32 | s.append(1, symbol[1]); 33 | s.append(n - 5, symbol[0]); 34 | } 35 | else if (n == 9) { 36 | s.append(1, symbol[0]); 37 | s.append(1, symbol[2]); 38 | } 39 | } 40 | }; -------------------------------------------------------------------------------- /PartitionList/PartitionList.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode *partition(ListNode *head, int x) { 12 | // Start typing your C/C++ solution below 13 | // DO NOT write int main() function 14 | 15 | ListNode less_than_head(0); 16 | ListNode no_less_than_head(0); 17 | ListNode *less_than = &less_than_head; 18 | ListNode *no_less_than = &no_less_than_head; 19 | 20 | ListNode *node = head; 21 | while (node != NULL) { 22 | if (node->val < x) { 23 | less_than->next = node; 24 | node = node->next; 25 | less_than = less_than->next; 26 | } 27 | else { 28 | no_less_than->next = node; 29 | node = node->next; 30 | no_less_than = no_less_than->next; 31 | } 32 | } 33 | no_less_than->next = NULL; 34 | less_than->next = no_less_than_head.next; 35 | return less_than_head.next; 36 | } 37 | }; -------------------------------------------------------------------------------- /SpiralMatrixII/SpiralMatrixII.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector > generateMatrix(int n) { 4 | vector> matrix(n, vector(n, 0)); 5 | int dir[4][2] = {0, 1, 1, 0, 0, -1, -1, 0}; 6 | int x = 0; 7 | int y = -1; 8 | int k = 0; 9 | int count = 0; 10 | int horizon = true; 11 | int row = n; 12 | int col = n + 1; 13 | while (count < n * n) { 14 | int dx = dir[k%4][0]; 15 | int dy = dir[k%4][1]; 16 | k++; 17 | if (horizon) { 18 | horizon = false; 19 | col--; 20 | for (int i = 0; i < col; i++) { 21 | x += dx; 22 | y += dy; 23 | count++; 24 | matrix[x][y] = count; 25 | } 26 | } else { 27 | horizon = true; 28 | row--; 29 | for (int i = 0; i < row; i++) { 30 | x += dx; 31 | y += dy; 32 | count++; 33 | matrix[x][y] = count; 34 | } 35 | } 36 | } 37 | return matrix; 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /SubstringwithConcatenationofAllWords/SubstringwithConcatenationofAllWords.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findSubstring(string S, vector &L) { 4 | vector result; 5 | if (L.empty()) { 6 | return result; 7 | } 8 | int n = L.size(); 9 | int len = L[0].size(); 10 | map hash; 11 | for (int i = 0; i < n; i++) { 12 | hash[L[i]] += 1; 13 | } 14 | for (int i = 0; i < len; i++) { 15 | vector slices; 16 | for (int j = i; j + len <= S.size(); j += len) { 17 | slices.push_back(S.substr(j, len)); 18 | } 19 | for (int j = 0; j + n <= slices.size(); j++) { 20 | map found; 21 | for (int k = 0; k < n; k++) { 22 | found[slices[j+k]] += 1; 23 | if (found[slices[j+k]] > hash[slices[j+k]]) { 24 | break; 25 | } 26 | if (k == n - 1) { 27 | result.push_back(i + j * len); 28 | } 29 | } 30 | } 31 | } 32 | return result; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /RotateList/RotateList.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode *rotateRight(ListNode *head, int k) { 12 | // Start typing your C/C++ solution below 13 | // DO NOT write int main() function 14 | 15 | if (head == NULL) return head; 16 | 17 | ListNode *node = head; 18 | int len = 0; 19 | while (node) { 20 | len += 1; 21 | node = node->next; 22 | } 23 | if (k >= len) 24 | k %= len; 25 | 26 | if (k == 0) 27 | return head; 28 | 29 | ListNode *slow = head; 30 | ListNode *fast = head; 31 | 32 | for (int i = 0; i < len - 1; i++) 33 | fast = fast->next; 34 | for (int i = 0; i < len - k - 1; i++) 35 | slow = slow->next; 36 | 37 | if (slow == fast) 38 | return head; 39 | 40 | ListNode *newHead = slow->next; 41 | slow->next = NULL; 42 | fast->next = head; 43 | return newHead; 44 | 45 | } 46 | }; -------------------------------------------------------------------------------- /WordLadder/WordLadder.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int ladderLength(string start, string end, unordered_set &dict) { 4 | queue q; 5 | unordered_map visited; 6 | map steps; 7 | 8 | q.push(start); 9 | visited[start] = true; 10 | while (!q.empty()) { 11 | string u = q.front(); 12 | q.pop(); 13 | if (u == end) { 14 | int count = 1; 15 | while (steps.find(u) != steps.end()) { 16 | u = steps[u]; 17 | count++; 18 | } 19 | return count; 20 | } 21 | string v = u; 22 | for (int i = 0; i < v.size(); i++) { 23 | for (char c = 'a'; c <= 'z'; c++) { 24 | v[i] = c; 25 | if (visited.find(v) == visited.end() 26 | && dict.find(v) != dict.end()) { 27 | visited[v] = true; 28 | steps[v] = u; 29 | q.push(v); 30 | } 31 | } 32 | v[i] = u[i]; 33 | } 34 | } 35 | return 0; 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /N-Queens/N-Queens.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector > solveNQueens(int n) { 4 | vector> result; 5 | if (n == 0) { 6 | return result; 7 | } 8 | vector sol(n, string(n, '.')); 9 | vector> visited(3, vector(2*n, false)); 10 | dfs(result, sol, visited, 0); 11 | return result; 12 | } 13 | 14 | void dfs(vector>& result, vector& sol, vector>& visited, int row) { 15 | int n = sol.size(); 16 | if (row == n) { 17 | result.push_back(sol); 18 | return; 19 | } 20 | for (int col = 0; col < n; col++) { 21 | if (visited[0][col] || visited[1][row+col] || visited[2][n-1-row+col]) { 22 | continue; 23 | } 24 | visited[0][col] = true; 25 | visited[1][row+col] = true; 26 | visited[2][n-1-row+col] = true; 27 | sol[row][col] = 'Q'; 28 | dfs(result, sol, visited, row + 1); 29 | sol[row][col] = '.'; 30 | visited[0][col] = false; 31 | visited[1][row+col] = false; 32 | visited[2][n-1-row+col] = false; 33 | } 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /PathSumII/PathSumII.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | vector > pathSum(TreeNode *root, int sum) { 13 | // Start typing your C/C++ solution below 14 | // DO NOT write int main() function 15 | vector> result; 16 | vector path; 17 | dfs(root, 0, sum, path, result); 18 | return move(result); 19 | 20 | } 21 | void dfs(TreeNode *node, int value, int sum, 22 | vector& path, vector>& result) { 23 | if (node == NULL) return; 24 | path.push_back(node->val); 25 | if (node->left == NULL && node->right == NULL) { 26 | if (node->val + value == sum) { 27 | result.push_back(path); 28 | } 29 | path.pop_back(); 30 | return; 31 | } 32 | if (node->left) 33 | dfs(node->left, node->val + value, sum, path, result); 34 | if (node->right) 35 | dfs(node->right, node->val + value, sum, path, result); 36 | path.pop_back(); 37 | } 38 | }; -------------------------------------------------------------------------------- /LargestRectangleinHistogram/LargestRectangleinHistogram.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int largestRectangleArea(vector& height) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | 7 | int n = height.size(); 8 | int width[n]; 9 | stack minHeight; 10 | 11 | for (int i = 0; i < n; i++) { 12 | while (!minHeight.empty() && height[i] <= height[minHeight.top()]) 13 | minHeight.pop(); 14 | int left = minHeight.empty() ? -1 : minHeight.top(); 15 | width[i] = i - left - 1; 16 | minHeight.push(i); 17 | } 18 | 19 | while (!minHeight.empty()) 20 | minHeight.pop(); 21 | 22 | for (int i = n - 1; i >= 0; i--) { 23 | while (!minHeight.empty() && height[i] <= height[minHeight.top()]) 24 | minHeight.pop(); 25 | int right = minHeight.empty() ? n : minHeight.top(); 26 | width[i] += right - i - 1; 27 | minHeight.push(i); 28 | } 29 | 30 | int result = 0; 31 | for (int i = 0; i < n; i++) 32 | result = max(result, height[i] * (width[i] + 1)); 33 | return result; 34 | } 35 | }; -------------------------------------------------------------------------------- /Searcha2DMatrix/Searcha2DMatrix.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool searchMatrix(vector>& matrix, int target) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | if (matrix.empty()) return false; 7 | int lf = 0; 8 | int rt = matrix.size() - 1; 9 | int column = matrix[0].size(); 10 | while (lf <= rt) { 11 | int m = (lf + rt) / 2; 12 | if (target < matrix[m][0]) { 13 | rt = m - 1; 14 | } 15 | else if (target > matrix[m][column-1]) { 16 | lf = m + 1; 17 | } 18 | else { 19 | return isValid(matrix[m], target); 20 | } 21 | } 22 | return false; 23 | } 24 | bool isValid(vector& row, int target) { 25 | int lf = 0; 26 | int rt = row.size() - 1; 27 | while (lf <= rt) { 28 | int m = (lf + rt) / 2; 29 | if (target == row[m]) { 30 | return true; 31 | } 32 | else if (target > row[m]) { 33 | lf = m + 1; 34 | } 35 | else { 36 | rt = m - 1; 37 | } 38 | } 39 | return false; 40 | } 41 | }; -------------------------------------------------------------------------------- /ConstructBinaryTreefromInorderandPostorderTraversal/ConstructBinaryTreefromInorderandPostorderTraversal.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | TreeNode *buildTree(vector &inorder, vector &postorder) { 13 | if (inorder.empty()) { 14 | return NULL; 15 | } 16 | return dfs(inorder, 0, inorder.size() - 1, postorder, 0, postorder.size() - 1); 17 | } 18 | TreeNode* dfs(vector& inorder, int l1, int r1, vector& postorder, int l2, int r2) { 19 | if (l1 > r1) { 20 | return NULL; 21 | } 22 | if (l1 == r1) { 23 | return new TreeNode(inorder[l1]); 24 | } 25 | TreeNode* root = new TreeNode(postorder[r2]); 26 | for (int i = l1; i <= r1; i++) { 27 | if (inorder[i] == postorder[r2]) { 28 | root->left = dfs(inorder, l1, i - 1, postorder, l2, l2 + i - l1 - 1); 29 | root->right = dfs(inorder, i + 1, r1, postorder, l2 + i - l1, r2 - 1); 30 | return root; 31 | } 32 | } 33 | return NULL; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /MinimumWindowSubstring/MinimumWindowSubstring.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string minWindow(string S, string T) { 4 | string result(""); 5 | map needed; 6 | map found; 7 | for (int i = 0; i < T.size(); i++) { 8 | needed[T[i]]++; 9 | } 10 | int count = 0; 11 | int minlen = S.size() + 1; 12 | for (int i = 0, j = 0; j < S.size(); j++) { 13 | if (needed[S[j]] == 0) { 14 | continue; 15 | } 16 | found[S[j]]++; 17 | if (found[S[j]] <= needed[S[j]]) { 18 | count++; 19 | } 20 | if (count == T.size()) { 21 | while (i <= j) { 22 | if (found[S[i]] == 0) { 23 | i++; 24 | } else if (found[S[i]] > needed[S[i]]) { 25 | found[S[i]]--; 26 | i++; 27 | } else { 28 | break; 29 | } 30 | } 31 | if (minlen > j - i + 1) { 32 | minlen = j - i + 1; 33 | result = S.substr(i, minlen); 34 | } 35 | } 36 | } 37 | return result; 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /ConstructBinaryTreefromPreorderandInorderTraversal/ConstructBinaryTreefromPreorderandInorderTraversal.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | TreeNode *buildTree(vector &preorder, vector &inorder) { 13 | if (preorder.size() == 0) { 14 | return NULL; 15 | } 16 | return dfs(preorder, 0, preorder.size() - 1, inorder, 0, inorder.size() - 1); 17 | } 18 | 19 | TreeNode* dfs(vector& preorder, int l1, int r1, vector& inorder, int l2, int r2) { 20 | if (l1 > r1) { 21 | return NULL; 22 | } 23 | if (l1 == r1) { 24 | return new TreeNode(preorder[l1]); 25 | } 26 | TreeNode* root = new TreeNode(preorder[l1]); 27 | for (int i = l2; i <= r2; i++) { 28 | if (inorder[i] == preorder[l1]) { 29 | root->left = dfs(preorder, l1 + 1, l1 + i - l2, inorder, l2, i - 1); 30 | root->right = dfs(preorder, l1 + i - l2 + 1, r1, inorder, i + 1, r2); 31 | return root; 32 | } 33 | } 34 | return NULL; 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /MergeTwoSortedLists/MergeTwoSortedLists.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { 12 | // Start typing your C/C++ solution below 13 | // DO NOT write int main() function 14 | 15 | ListNode prev_head(0); 16 | ListNode *sorted_list = &prev_head; 17 | 18 | while (l1 && l2) { 19 | if (l1->val < l2->val) { 20 | sorted_list->next = l1; 21 | l1 = l1->next; 22 | sorted_list = sorted_list->next; 23 | } 24 | else { 25 | sorted_list->next = l2; 26 | l2 = l2->next; 27 | sorted_list = sorted_list->next; 28 | } 29 | } 30 | 31 | while (l1) { 32 | sorted_list->next = l1; 33 | l1 = l1->next; 34 | sorted_list = sorted_list->next; 35 | } 36 | while (l2) { 37 | sorted_list->next = l2; 38 | l2 = l2->next; 39 | sorted_list = sorted_list->next; 40 | } 41 | return prev_head.next; 42 | } 43 | }; -------------------------------------------------------------------------------- /CombinationSumII/CombinationSumII.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> combinationSum2(vector& candidates, int target) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | 7 | combination_set.clear(); 8 | sort(candidates.begin(), candidates.end()); 9 | vector nums; 10 | DFS(nums, target, candidates, 0); 11 | return move(combination_set); 12 | } 13 | 14 | void DFS(vector& nums, int target, vector& candidates, int position) { 15 | if (target < 0) return; 16 | 17 | if (target == 0) { 18 | if (find(combination_set.begin(), combination_set.end(), nums) == combination_set.end()) 19 | combination_set.push_back(nums); 20 | return; 21 | } 22 | 23 | if (position >= candidates.size()) 24 | return; 25 | 26 | DFS(nums, target, candidates, position + 1); 27 | 28 | int value = candidates[position]; 29 | if (value <= target) { 30 | nums.push_back(value); 31 | DFS(nums, target - value, candidates, position + 1); 32 | nums.pop_back(); 33 | } 34 | } 35 | private: 36 | vector> combination_set; 37 | }; -------------------------------------------------------------------------------- /ScrambleString/ScrambleString.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isScramble(string s1, string s2) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | 7 | return isScrambleHelper(s1, 0, s2, 0, s1.size()); 8 | } 9 | 10 | bool isScrambleHelper(string& s1, int l1, string& s2, int l2, int size) { 11 | if (!canScramble(s1, l1, s2, l2, size)) return false; 12 | if (size == 1) return true; 13 | 14 | for (int i = 1; i < size; i++) { 15 | if (isScrambleHelper(s1, l1, s2, l2 + size - i, i) && 16 | isScrambleHelper(s1, l1 + i, s2, l2, size - i)) 17 | return true; 18 | if (isScrambleHelper(s1, l1, s2, l2, i) && 19 | isScrambleHelper(s1, l1 + i, s2, l2 + i, size - i)) 20 | return true; 21 | } 22 | return false; 23 | } 24 | 25 | bool canScramble(string& s1, int l1, string& s2, int l2, int size) { 26 | int hash[26] = {0}; 27 | for (int i = 0; i < size; i++) { 28 | hash[s1[l1 + i] - 'a'] += 1; 29 | hash[s2[l2 + i] - 'a'] -= 1; 30 | } 31 | for (int i = 0; i < 26; i++) { 32 | if (hash[i]) return false; 33 | } 34 | return true; 35 | } 36 | }; -------------------------------------------------------------------------------- /SpiralMatrix/SpiralMatrix.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector spiralOrder(vector > &matrix) { 4 | vector result; 5 | if (matrix.empty()) { 6 | return result; 7 | } 8 | int row = matrix.size(); 9 | int col = matrix[0].size() + 1; 10 | int dir[4][2] = {0, 1, 1, 0, 0, -1, -1, 0}; 11 | int x = 0; 12 | int y = -1; 13 | int k = 0; 14 | int count = 0; 15 | bool horizon = true; 16 | while (count < matrix.size() * matrix[0].size()) { 17 | int dx = dir[k%4][0]; 18 | int dy = dir[k%4][1]; 19 | k++; 20 | 21 | if (horizon) { 22 | horizon = false; 23 | col--; 24 | for (int i = 0; i < col; i++, count++) { 25 | x += dx; 26 | y += dy; 27 | result.push_back(matrix[x][y]); 28 | } 29 | } else { 30 | horizon = true; 31 | row--; 32 | for (int i = 0; i < row; i++, count++) { 33 | x += dx; 34 | y += dy; 35 | result.push_back(matrix[x][y]); 36 | } 37 | } 38 | } 39 | return result; 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /MedianofTwoSortedArrays/MedianofTwoSortedArrays.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | double findMedianSortedArrays(int A[], int m, int B[], int n) { 4 | if ((m + n) & 1) { 5 | return findKth((m + n - 1) / 2, A, 0, m - 1, B, 0, n - 1); 6 | } else { 7 | int x = findKth((m + n) / 2 - 1, A, 0, m - 1, B, 0, n - 1); 8 | int y = findKth((m + n) / 2, A, 0, m - 1, B, 0, n - 1); 9 | return (x + y) / 2.0; 10 | } 11 | } 12 | int findKth(int k, int A[], int l1, int r1, int B[], int l2, int r2) { 13 | if (l1 > r1) { 14 | return B[l2 + k]; 15 | } 16 | if (l2 > r2) { 17 | return A[l1 + k]; 18 | } 19 | int m1 = (l1 + r1) / 2; 20 | int m2 = (l2 + r2) / 2; 21 | if (A[m1] > B[m2]) { 22 | if (k + 1 < m1 - l1 + 1 + m2 - l2 + 1) { 23 | return findKth(k, A, l1, m1 - 1, B, l2, r2); 24 | } else { 25 | return findKth(k - (m2 - l2 + 1), A, l1, r1, B, m2 + 1, r2); 26 | } 27 | } else { 28 | if (k + 1 < m1 - l1 + 1 + m2 - l2 + 1) { 29 | return findKth(k, A, l1, r1, B, l2, m2 - 1); 30 | } else { 31 | return findKth(k - (m1 - l1 + 1), A, m1 + 1, r1, B, l2, r2); 32 | } 33 | } 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /EvaluateReversePolishNotation/EvaluateReversePolishNotation.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int evalRPN(vector &tokens) { 4 | stack nums; 5 | stack ops; 6 | 7 | for (int i = 0; i < tokens.size(); i++) { 8 | if (tokens[i][0] >= '0' && tokens[i][0] <= '9') { 9 | int value = atoi(tokens[i].c_str()); 10 | nums.push(value); 11 | } else if (tokens[i].size() >= 2) { 12 | int value = atoi(tokens[i].c_str()); 13 | nums.push(value); 14 | } else { 15 | int b = nums.top(); 16 | nums.pop(); 17 | int a = nums.top(); 18 | nums.pop(); 19 | int c; 20 | switch (tokens[i][0]) { 21 | case '+': 22 | c = a + b; 23 | break; 24 | case '-': 25 | c = a - b; 26 | break; 27 | case '*': 28 | c = a * b; 29 | break; 30 | case '/': 31 | c = a / b; 32 | break; 33 | } 34 | nums.push(c); 35 | } 36 | } 37 | return nums.top(); 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /SurroundedRegions/SurroundedRegions.cpp: -------------------------------------------------------------------------------- 1 | 2 | const int dx[4] = {0, 0, 1, -1}; 3 | const int dy[4] = {1, -1, 0, 0}; 4 | 5 | class Solution { 6 | public: 7 | void solve(vector> &board) { 8 | // Start typing your C/C++ solution below 9 | // DO NOT write int main() function 10 | 11 | if (board.empty()) return; 12 | 13 | row = board.size(); 14 | col = board[0].size(); 15 | 16 | for (int i = 0; i < row; i++) { 17 | if (board[i][0] == 'O') dfs(i, 0, board); 18 | if (board[i][col-1] == 'O') dfs(i, col-1, board); 19 | } 20 | for (int j = 1; j < col; j++) { 21 | if (board[0][j] == 'O') dfs(0, j, board); 22 | if (board[row-1][j] == 'O') dfs(row-1, j, board); 23 | } 24 | for (int i = 0; i < row; i++) { 25 | for (int j = 0; j < col; j++) { 26 | if (board[i][j] == 'O') board[i][j] = 'X'; 27 | else if (board[i][j] == 'B') board[i][j] = 'O'; 28 | } 29 | } 30 | } 31 | 32 | void dfs(int x, int y, vector> &board) { 33 | board[x][y] = 'B'; 34 | 35 | for (int k = 0; k < 4; k++) { 36 | int i = x + dx[k]; 37 | int j = y + dy[k]; 38 | if (check(i, j) && board[i][j] == 'O') { 39 | dfs(i, j, board); 40 | } 41 | } 42 | } 43 | 44 | bool check(int x, int y) { 45 | if (x >= 0 && x < row && y >= 0 && y < col) { 46 | return true; 47 | } 48 | return false; 49 | } 50 | private: 51 | int row, col; 52 | }; 53 | -------------------------------------------------------------------------------- /CombinationSum/CombinationSum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector > combinationSum(vector &candidates, int target) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | 7 | combination_set.clear(); 8 | sort(candidates.begin(), candidates.end()); 9 | vector nums; 10 | DFS(nums, target, candidates, 0); 11 | return move(combination_set); 12 | } 13 | 14 | void DFS(vector& nums, int target, vector& candidates, int position) { 15 | if (target < 0) return; 16 | 17 | if (target == 0) { 18 | combination_set.push_back(nums); 19 | return; 20 | } 21 | 22 | if (position >= candidates.size()) 23 | return; 24 | 25 | DFS(nums, target, candidates, position + 1); 26 | 27 | int value = candidates[position]; 28 | 29 | for (int i = 1; i * value <= target; i++) { 30 | for (int j = 0; j < i; j++) 31 | nums.push_back(value); 32 | 33 | DFS(nums, target - i * value, candidates, position + 1); 34 | 35 | for (int j = 0; j < i; j++) 36 | nums.pop_back(); 37 | } 38 | } 39 | 40 | private: 41 | vector> combination_set; 42 | }; -------------------------------------------------------------------------------- /InterleavingString/InterleavingString.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isInterleave(string s1, string s2, string s3) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | 7 | int M = s1.size(); 8 | int N = s2.size(); 9 | 10 | if (M + N != s3.size()) return false; 11 | 12 | vector> dp(2, vector(N + 1, false)); 13 | dp[0][0] = true; 14 | for (int j = 1; j <= N; j++) { 15 | if (s2[j-1] == s3[j-1]) 16 | dp[0][j] = true; 17 | else 18 | break; 19 | } 20 | int T1 = 1, T2 = 0; 21 | for (int i = 1; i <= M; i++) { 22 | T1 ^= 1, T2 ^= 1; 23 | dp[T2][0] = dp[T1][0] && s1[i-1] == s3[i-1]; 24 | for (int j = 1; j <= N; j++) { 25 | if (s3[i+j-1] == s1[i-1] && s3[i+j-1] == s2[j-1]) 26 | dp[T2][j] = dp[T1][j] | dp[T2][j-1]; 27 | else if (s3[i+j-1] == s1[i-1] && s3[i+j-1] != s2[j-1]) 28 | dp[T2][j] = dp[T1][j]; 29 | else if (s3[i+j-1] != s1[i-1] && s3[i+j-1] == s2[j-1]) 30 | dp[T2][j] = dp[T2][j-1]; 31 | else 32 | dp[T2][j] = false; 33 | } 34 | } 35 | return dp[T2][N]; 36 | } 37 | }; -------------------------------------------------------------------------------- /SearchforaRange/SearchforaRange.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector searchRange(int A[], int n, int target) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | 7 | vector range; 8 | range.push_back(find_lower_bound(A, n, target)); 9 | range.push_back(find_upper_bound(A, n, target)); 10 | return range; 11 | } 12 | 13 | int find_lower_bound(int A[], int n, int target) { 14 | int left = 0, right = n - 1; 15 | while (left <= right) { 16 | int mid = left + (right - left) / 2; 17 | if (A[mid] >= target) { 18 | right = mid - 1; 19 | } 20 | else { 21 | left = mid + 1; 22 | } 23 | } 24 | if (A[left] == target) 25 | return left; 26 | return -1; 27 | } 28 | 29 | int find_upper_bound(int A[], int n, int target) { 30 | int left = 0, right = n - 1; 31 | while (left <= right) { 32 | int mid = left + (right - left) / 2; 33 | if (A[mid] <= target) { 34 | left = mid + 1; 35 | } 36 | else { 37 | right = mid - 1; 38 | } 39 | } 40 | if (A[right] == target) 41 | return right; 42 | return -1; 43 | } 44 | }; -------------------------------------------------------------------------------- /UniqueBinarySearchTreesII/UniqueBinarySearchTreesII.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | vector generateTrees(int n) { 13 | // Start typing your C/C++ solution below 14 | // DO NOT write int main() function 15 | 16 | return generateTreesHelper(1, n); 17 | } 18 | 19 | vector generateTreesHelper(int left, int right) { 20 | vector trees; 21 | if (left > right) { 22 | trees.push_back(NULL); 23 | return trees; 24 | } 25 | for (int r = left; r <= right; r++) { 26 | vector left_trees = generateTreesHelper(left, r - 1); 27 | vector right_trees = generateTreesHelper(r + 1, right); 28 | for (int i = 0; i < left_trees.size(); i++) { 29 | for (int j = 0; j < right_trees.size(); j++) { 30 | TreeNode *root = new TreeNode(r); 31 | root->left = left_trees[i]; 32 | root->right = right_trees[j]; 33 | trees.push_back(root); 34 | } 35 | } 36 | } 37 | return trees; 38 | } 39 | }; -------------------------------------------------------------------------------- /PalindromePartitioning/PalindromePartitioning.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector > partition(string s) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | 7 | ans.clear(); 8 | dynamic(s); 9 | vector v; 10 | dfs(s, 0, v); 11 | return ans; 12 | 13 | } 14 | void dfs(string& s, int p, vector& v) { 15 | if (p == s.size()) { 16 | ans.push_back(v); 17 | return ; 18 | } 19 | string temp; 20 | bool flag = false; 21 | for (int i = p; i < s.size(); i++) { 22 | temp += s[i]; 23 | if (dp[p][i]) { 24 | v.push_back(temp); 25 | dfs(s, i+1, v); 26 | v.pop_back(); 27 | } 28 | } 29 | } 30 | 31 | void dynamic(string& s) { 32 | memset(dp, false, sizeof(dp)); 33 | int len = s.size(); 34 | for (int i = 0; i < len; i++) 35 | dp[i][i] = true, dp[i+1][i] = true; 36 | for (int d = 1; d < len; d++) { 37 | for (int i = 0, j = i+d; j < len; i++, j++) { 38 | if (s[i] == s[j]) 39 | dp[i][j] |= dp[i+1][j-1]; 40 | } 41 | } 42 | } 43 | private: 44 | vector > ans; 45 | bool dp[1000][1000]; 46 | }; 47 | -------------------------------------------------------------------------------- /ConvertSortedListtoBinarySearchTree/ConvertSortedListtoBinarySearchTree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | /** 10 | * Definition for binary tree 11 | * struct TreeNode { 12 | * int val; 13 | * TreeNode *left; 14 | * TreeNode *right; 15 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 16 | * }; 17 | */ 18 | class Solution { 19 | public: 20 | TreeNode *sortedListToBST(ListNode *head) { 21 | if (head == NULL) { 22 | return NULL; 23 | } 24 | if (head->next == NULL) { 25 | return new TreeNode(head->val); 26 | } 27 | ListNode prevhead(0); 28 | prevhead.next = head; 29 | ListNode* prev = &prevhead; 30 | ListNode* one = head; 31 | ListNode* two = head; 32 | while (two && two->next) { 33 | prev = prev->next; 34 | one = one->next; 35 | two = two->next->next; 36 | } 37 | TreeNode* root = new TreeNode(one->val); 38 | ListNode* temp = one->next; 39 | prev->next = NULL; 40 | one->next = NULL; 41 | root->left = sortedListToBST(head); 42 | root->right = sortedListToBST(temp); 43 | return root; 44 | } 45 | }; 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /MultiplyStrings/MultiplyStrings.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string multiply(string num1, string num2) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | 7 | int len_num1 = num1.size(); 8 | int len_num2 = num2.size(); 9 | 10 | vector multiply_num(len_num1 + len_num2, 0); 11 | 12 | for (int i = len_num1 - 1; i >= 0; i--) { 13 | for (int j = len_num2 - 1; j >= 0; j--) { 14 | int a = num1[i] - '0'; 15 | int pa = len_num1 - i - 1; 16 | int b = num2[j] - '0'; 17 | int pb = len_num2 - j - 1; 18 | multiply_num[pa + pb] += a * b; 19 | } 20 | } 21 | for (int i = 0; i < multiply_num.size(); i++) { 22 | if (multiply_num[i] > 0) { 23 | multiply_num[i+1] += multiply_num[i] / 10; 24 | multiply_num[i] = multiply_num[i] % 10; 25 | } 26 | } 27 | 28 | while (multiply_num[multiply_num.size()-1] == 0) 29 | multiply_num.pop_back(); 30 | 31 | string num; 32 | for (auto iter = multiply_num.rbegin(); iter != multiply_num.rend(); iter++) 33 | num += (char)(*iter + '0'); 34 | 35 | if (num.empty()) 36 | num = "0"; 37 | 38 | return num; 39 | } 40 | }; -------------------------------------------------------------------------------- /3Sum/3Sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector > threeSum(vector &num) { 4 | vector> result; 5 | if (num.empty()) { 6 | return result; 7 | } 8 | sort(num.begin(), num.end()); 9 | for (int start = 0; start < num.size(); start++) { 10 | int i = start + 1; 11 | int j = num.size() - 1; 12 | int target = -num[start]; 13 | while (i < j) { 14 | if (num[i] + num[j] == target) { 15 | vector triple; 16 | triple.push_back(num[start]); 17 | triple.push_back(num[i]); 18 | triple.push_back(num[j]); 19 | result.push_back(triple); 20 | while (i + 1 < num.size() && num[i] == num[i+1]) { 21 | i++; 22 | } 23 | while (j - 1 >= 0 && num[j] == num[j-1]) { 24 | j--; 25 | } 26 | i++; 27 | j--; 28 | } else if (num[i] + num[j] < target) { 29 | i++; 30 | } else { 31 | j--; 32 | } 33 | } 34 | while (start + 1 < num.size() && num[start] == num[start+1]) { 35 | start++; 36 | } 37 | } 38 | return result; 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /InsertInterval/InsertInterval.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for an interval. 3 | * struct Interval { 4 | * int start; 5 | * int end; 6 | * Interval() : start(0), end(0) {} 7 | * Interval(int s, int e) : start(s), end(e) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | vector insert(vector &intervals, Interval newInterval) { 13 | // Start typing your C/C++ solution below 14 | // DO NOT write int main() function 15 | 16 | vector merged_interval; 17 | 18 | bool has_inserted = false; 19 | int new_start = newInterval.start; 20 | int new_end = newInterval.end; 21 | 22 | for (int i = 0; i < intervals.size(); i++) { 23 | if (intervals[i].start <= new_end && new_start <= intervals[i].end) { 24 | new_start = min(new_start, intervals[i].start); 25 | new_end = max(new_end, intervals[i].end); 26 | } 27 | else { 28 | if (!has_inserted && new_end < intervals[i].start) { 29 | has_inserted = true; 30 | merged_interval.push_back(Interval(new_start, new_end)); 31 | } 32 | merged_interval.push_back(intervals[i]); 33 | } 34 | } 35 | if (!has_inserted) 36 | merged_interval.push_back(Interval(new_start, new_end)); 37 | return merged_interval; 38 | } 39 | }; -------------------------------------------------------------------------------- /MergekSortedLists/MergekSortedLists.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode *mergeKLists(vector &lists) { 12 | return merge(lists, 0, lists.size() - 1); 13 | } 14 | ListNode* merge(vector& lists, int left, int right) { 15 | if (left > right) { 16 | return NULL; 17 | } 18 | if (left == right) { 19 | return lists[left]; 20 | } 21 | int mid = (left + right) / 2; 22 | ListNode* l1 = merge(lists, left, mid); 23 | ListNode* l2 = merge(lists, mid + 1, right); 24 | 25 | ListNode head(0); 26 | ListNode* curr = &head; 27 | while (l1 && l2) { 28 | if (l1->val < l2->val) { 29 | curr->next = l1; 30 | l1 = l1->next; 31 | } else { 32 | curr->next = l2; 33 | l2 = l2->next; 34 | } 35 | curr = curr->next; 36 | } 37 | while (l1) { 38 | curr->next = l1; 39 | l1 = l1->next; 40 | curr = curr->next; 41 | } 42 | while (l2) { 43 | curr->next = l2; 44 | l2 = l2->next; 45 | curr = curr->next; 46 | } 47 | return head.next; 48 | } 49 | }; 50 | -------------------------------------------------------------------------------- /LongestValidParentheses/LongestValidParentheses.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestValidParentheses(string s) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | 7 | int n = s.size(); 8 | int max_valid = 0; 9 | int count_left = 0, valid_count = 0; 10 | 11 | for (int i = 0; i < n; i++) { 12 | if (s[i] == '(') { 13 | count_left += 1; 14 | valid_count += 1; 15 | } else { 16 | valid_count -= 1; 17 | } 18 | 19 | if (valid_count < 0) { 20 | valid_count = 0; 21 | count_left = 0; 22 | } else if (valid_count == 0) { 23 | max_valid = max(max_valid, count_left); 24 | } 25 | } 26 | 27 | valid_count = 0; 28 | int count_right = 0; 29 | for (int i = n - 1; i >= 0; i--) { 30 | if (s[i] == ')') { 31 | count_right += 1; 32 | valid_count += 1; 33 | } else { 34 | valid_count -= 1; 35 | } 36 | 37 | if (valid_count < 0) { 38 | valid_count = 0; 39 | count_right = 0; 40 | } else if (valid_count == 0) { 41 | max_valid = max(max_valid, count_right); 42 | } 43 | } 44 | return 2 * max_valid; 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /BinaryTreeLevelOrderTraversal/BinaryTreeLevelOrderTraversal.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | vector > levelOrder(TreeNode *root) { 13 | // Start typing your C/C++ solution below 14 | // DO NOT write int main() function 15 | 16 | vector> result; 17 | if (root == NULL) return result; 18 | 19 | queue nodeQueue; 20 | vector value; 21 | nodeQueue.push(root); 22 | int nodeNow = 1; 23 | int nodeNext = 0; 24 | 25 | while (!nodeQueue.empty()) { 26 | TreeNode *node = nodeQueue.front(); 27 | nodeQueue.pop(); 28 | nodeNow -= 1; 29 | value.push_back(node->val); 30 | if (node->left) { 31 | nodeQueue.push(node->left); 32 | nodeNext += 1; 33 | } 34 | if (node->right) { 35 | nodeQueue.push(node->right); 36 | nodeNext += 1; 37 | } 38 | if (nodeNow == 0) { 39 | result.push_back(value); 40 | value.clear(); 41 | nodeNow = nodeNext; 42 | nodeNext = 0; 43 | } 44 | } 45 | return move(result); 46 | } 47 | }; -------------------------------------------------------------------------------- /RecoverBinarySearchTree/RecoverBinarySearchTree.cpp: -------------------------------------------------------------------------------- 1 | // O(n) time, O(1) space 2 | class Solution { 3 | public: 4 | void recoverTree(TreeNode *root) { 5 | TreeNode* node = root; 6 | TreeNode* prev = NULL; 7 | TreeNode* prev1 = NULL; 8 | TreeNode* curr1 = NULL; 9 | TreeNode* prev2 = NULL; 10 | TreeNode* curr2 = NULL; 11 | 12 | while (node != NULL) { 13 | if (node->left == NULL) { 14 | prev = node; 15 | node = node->right; 16 | } else { 17 | TreeNode* next = node->left; 18 | while (next->right && next->right != node) { 19 | next = next->right; 20 | } 21 | if (next->right == NULL) { 22 | next->right = node; 23 | node = node->left; 24 | } else { 25 | prev = node; 26 | node = node->right; 27 | next->right = NULL; 28 | } 29 | } 30 | if (prev && node && prev->val > node->val) { 31 | if (prev1 == NULL) { 32 | prev1 = prev, curr1 = node; 33 | } else { 34 | prev2 = prev, curr2 = node; 35 | } 36 | } 37 | } 38 | if (prev1 && curr2) { 39 | swap(prev1->val, curr2->val); 40 | } else { 41 | swap(prev1->val, curr1->val); 42 | } 43 | } 44 | }; 45 | -------------------------------------------------------------------------------- /BestTimetoBuyandSellStockII/BestTimetoBuyandSellStockII.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(vector& prices) { 4 | 5 | if (prices.empty()) return 0; 6 | 7 | int maxprofit = 0; 8 | int minvalue = INFS; 9 | for (size_t i = 0; i < prices.size(); i++) { 10 | minvalue = min(prices[i], minvalue); 11 | int profit = prices[i] - minvalue; 12 | if (profit > 0) { 13 | maxprofit += profit; 14 | minvalue = prices[i]; 15 | } 16 | } 17 | return maxprofit; 18 | } 19 | // 20 | // firstly I thought this is a dynamic programming problem 21 | // but unfortunately, TLE in O(n^2) 22 | // It's a greed problem in O(n) 23 | // 24 | int maxProfit2(vector &prices) { 25 | // Start typing your C/C++ solution below 26 | // DO NOT write int main() function 27 | if (prices.empty()) return 0; 28 | 29 | vector dp(prices.size()); 30 | dp[0] = 0; 31 | for (size_t i = 1; i < prices.size(); i++) { 32 | int maxvalue = prices[i]; 33 | int maxprofit = 0; 34 | for (int j = i-1; j >= 0; j--) { 35 | maxvalue = max(maxvalue, prices[j]); 36 | maxprofit = max(maxprofit, maxvalue - prices[j]); 37 | dp[i] = max(dp[i], dp[j] + maxprofit); 38 | } 39 | } 40 | return dp[prices.size()-1]; 41 | } 42 | private: 43 | static const int INFS = 0x3FFFFFFF; 44 | }; 45 | -------------------------------------------------------------------------------- /BinaryTreeLevelOrderTraversalII/BinaryTreeLevelOrderTraversalII.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | vector > levelOrderBottom(TreeNode *root) { 13 | // Start typing your C/C++ solution below 14 | // DO NOT write int main() function 15 | 16 | vector> result; 17 | if (root == NULL) return result; 18 | 19 | queue nodeQueue; 20 | vector value; 21 | nodeQueue.push(root); 22 | int nodeNow = 1; 23 | int nodeNext = 0; 24 | 25 | while (!nodeQueue.empty()) { 26 | TreeNode *node = nodeQueue.front(); 27 | nodeQueue.pop(); 28 | nodeNow -= 1; 29 | value.push_back(node->val); 30 | if (node->left) { 31 | nodeQueue.push(node->left); 32 | nodeNext += 1; 33 | } 34 | if (node->right) { 35 | nodeQueue.push(node->right); 36 | nodeNext += 1; 37 | } 38 | if (nodeNow == 0) { 39 | result.push_back(value); 40 | value.clear(); 41 | nodeNow = nodeNext; 42 | nodeNext = 0; 43 | } 44 | } 45 | reverse(result.begin(), result.end()); 46 | return move(result); 47 | } 48 | }; -------------------------------------------------------------------------------- /MaximumSubarray/MaximumSubarray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxSubArray(int A[], int n) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | 7 | int maxsum = A[0]; 8 | int tempsum = A[0]; 9 | for (int i = 1; i < n; i++) { 10 | if (tempsum < 0) tempsum = 0; 11 | tempsum += A[i]; 12 | maxsum = max(maxsum, tempsum); 13 | } 14 | return maxsum; 15 | } 16 | }; 17 | 18 | // 19 | // solution 2 : divide and conquer 20 | // 21 | class Solution { 22 | public: 23 | int maxSubArray(int A[], int n) { 24 | // Start typing your C/C++ solution below 25 | // DO NOT write int main() function 26 | 27 | return maxSubArray(A, 0, n - 1); 28 | } 29 | 30 | int maxSubArray(int A[], int left, int right) { 31 | if (left > right) 32 | return INT_MIN; 33 | 34 | int mid = (left + right) / 2; 35 | int lmax = maxSubArray(A, left, mid - 1); 36 | int rmax = maxSubArray(A, mid + 1, right); 37 | 38 | int sum = 0, mlmax = 0; 39 | for (int i = mid - 1; i >= left; i--) { 40 | sum += A[i]; 41 | mlmax = max(mlmax, sum); 42 | } 43 | sum = 0; 44 | int mrmax = 0; 45 | for (int i = mid + 1; i <= right; i++) { 46 | sum += A[i]; 47 | mrmax = max(mrmax, sum); 48 | } 49 | 50 | return max(mlmax + A[mid] + mrmax, max(lmax, rmax)); 51 | } 52 | }; -------------------------------------------------------------------------------- /LRUCache/LRUCache.cc: -------------------------------------------------------------------------------- 1 | class LRUCache{ 2 | public: 3 | LRUCache(int capacity) { 4 | cap_ = capacity; 5 | dummy_.prev = &dummy_; 6 | dummy_.next = &dummy_; 7 | } 8 | 9 | int get(int key) { 10 | if (cache_.find(key) == cache_.end()) { 11 | return -1; 12 | } 13 | entry* e = cache_[key]; 14 | e->prev = &dummy_; 15 | e->next = dummy_.next; 16 | dummy_.next->prev = e; 17 | dummy_.next = e; 18 | 19 | return e->val; 20 | } 21 | 22 | void set(int key, int value) { 23 | while (cache_.size() >= cap_) { 24 | entry* e = dummy_.prev; 25 | e->prev->next = &dummy_; 26 | dummy_.prev = e->prev; 27 | 28 | cache_.erase(e->key); 29 | delete(e); 30 | } 31 | 32 | entry* e; 33 | if (cache_.find(key) == cache_.end()) { 34 | e = new(entry); 35 | cache_[key] = e; 36 | } else { 37 | e = cache_[key]; 38 | e->prev->next = e->next; 39 | e->next->prev = e->prev; 40 | } 41 | e->prev = &dummy_; 42 | e->next = dummy_.next; 43 | dummy_.next->prev = e; 44 | dummy_.next = e; 45 | 46 | e->val = value; 47 | } 48 | 49 | private: 50 | struct entry { 51 | int key; 52 | int val; 53 | entry* prev; 54 | entry* next; 55 | }; 56 | 57 | int cap_; 58 | map cache_; 59 | struct entry dummy_; 60 | }; 61 | -------------------------------------------------------------------------------- /SetMatrixZeroes/SetMatrixZeroes.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void setZeroes(vector>& matrix) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | 7 | if (matrix.empty()) return; 8 | 9 | bool rowzero = false; 10 | bool colzero = false; 11 | int row = matrix.size(); 12 | int col = matrix[0].size(); 13 | 14 | for (int i = 0; i < row; i++) { 15 | if (matrix[i][0] == 0) colzero = true; 16 | } 17 | for (int i = 0; i < col; i++) { 18 | if (matrix[0][i] == 0) rowzero = true; 19 | } 20 | for (int i = 1; i < row; i++) { 21 | for (int j = 1; j < col; j++) { 22 | if (matrix[i][j] == 0) { 23 | matrix[i][0] = matrix[0][j] = 0; 24 | } 25 | } 26 | } 27 | for (int i = 1; i < row; i++) { 28 | if (matrix[i][0] == 0) { 29 | for (int j = 1; j < col; j++) 30 | matrix[i][j] = 0; 31 | } 32 | } 33 | for (int j = 1; j < col; j++) { 34 | if (matrix[0][j] == 0) { 35 | for (int i = 1; i < row; i++) 36 | matrix[i][j] = 0; 37 | } 38 | } 39 | if (rowzero) { 40 | for (int j = 0; j < col; j++) 41 | matrix[0][j] = 0; 42 | } 43 | if (colzero) { 44 | for (int i = 0; i < row; i++) 45 | matrix[i][0] = 0; 46 | } 47 | } 48 | }; -------------------------------------------------------------------------------- /PopulatingNextRightPointersinEachNodeII/PopulatingNextRightPointersinEachNodeII.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree with next pointer. 3 | * struct TreeLinkNode { 4 | * int val; 5 | * TreeLinkNode *left, *right, *next; 6 | * TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | void connect(TreeLinkNode *root) { 12 | if (root == NULL) { 13 | return; 14 | } 15 | TreeLinkNode* leftmost = root; 16 | while (leftmost) { 17 | TreeLinkNode* node = leftmost; 18 | TreeLinkNode* prev = NULL; 19 | leftmost = NULL; 20 | while (node) { 21 | if (node->left) { 22 | if (leftmost == NULL) { 23 | leftmost = node->left; 24 | } 25 | if (prev == NULL) { 26 | prev = node->left; 27 | } else { 28 | prev->next = node->left; 29 | prev = node->left; 30 | } 31 | } 32 | if (node->right) { 33 | if (leftmost == NULL) { 34 | leftmost = node->right; 35 | } 36 | if (prev == NULL) { 37 | prev = node->right; 38 | } else { 39 | prev->next = node->right; 40 | prev = node->right; 41 | } 42 | } 43 | node = node->next; 44 | } 45 | } 46 | } 47 | }; 48 | -------------------------------------------------------------------------------- /BinaryTreePostorderTraversal/BinaryTreePostorderTraversal.cc: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | void print(vector& result, TreeNode* from, TreeNode* to) { 13 | vector temp; 14 | while (true) { 15 | temp.push_back(from->val); 16 | if (from == to) { 17 | break; 18 | } 19 | from = from->right; 20 | } 21 | for (int i = temp.size() - 1; i >= 0; i--) { 22 | result.push_back(temp[i]); 23 | } 24 | } 25 | 26 | vector postorderTraversal(TreeNode *root) { 27 | vector result; 28 | TreeNode prev(0); 29 | prev.left = root; 30 | TreeNode* curr = &prev; 31 | while (curr != NULL) { 32 | if (curr->left == NULL) { 33 | curr = curr->right; 34 | } else { 35 | TreeNode* next = curr->left; 36 | while (next->right && next->right != curr) { 37 | next = next->right; 38 | } 39 | if (next->right == NULL) { 40 | next->right = curr; 41 | curr = curr->left; 42 | } else { 43 | print(result, curr->left, next); 44 | next->right = NULL; 45 | curr = curr->right; 46 | } 47 | } 48 | } 49 | return result; 50 | } 51 | }; 52 | -------------------------------------------------------------------------------- /WildcardMatching/WildcardMatching.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isMatch(const char *s, const char *p) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | 7 | if (s == NULL || p == NULL) 8 | return false; 9 | 10 | int slen = strlen(s); 11 | int plen = strlen(p); 12 | 13 | int count_char = 0; 14 | for (int i = 0; i < plen; i++) { 15 | if (p[i] != '*') 16 | count_char += 1; 17 | } 18 | 19 | if (count_char > slen) 20 | return false; 21 | 22 | bool matches[slen + 1]; 23 | memset(matches, false, sizeof(bool)*(slen+1)); 24 | int first_match = 0; 25 | matches[first_match] = true; 26 | 27 | for (int i = 0; i < plen; i++) { 28 | if (i > 0 && p[i] == '*' && p[i-1] == '*') 29 | continue; 30 | if (p[i] == '*') { 31 | for (int j = first_match + 1; j <= slen; j++) 32 | matches[j] = true; 33 | } else { 34 | int match_id = -1; 35 | for (int j = slen; j > first_match; j--) { 36 | matches[j] = (s[j-1] == p[i] || p[i] == '?') && matches[j-1]; 37 | if (matches[j]) 38 | match_id = j; 39 | } 40 | if (match_id != -1) 41 | first_match = match_id; 42 | else 43 | return false; 44 | } 45 | } 46 | return matches[slen]; 47 | } 48 | }; -------------------------------------------------------------------------------- /BinaryTreeZigzagLevelOrderTraversal/BinaryTreeZigzagLevelOrderTraversal.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | vector> zigzagLevelOrder(TreeNode *root) { 13 | // Start typing your C/C++ solution below 14 | // DO NOT write int main() function 15 | 16 | vector> result; 17 | if (root == NULL) return result; 18 | 19 | stack stackNow; 20 | stack stackNext; 21 | vector value; 22 | bool left2right = true; 23 | stackNow.push(root); 24 | 25 | while (!stackNow.empty()) { 26 | TreeNode *node = stackNow.top(); 27 | stackNow.pop(); 28 | value.push_back(node->val); 29 | if (left2right) { 30 | if (node->left) 31 | stackNext.push(node->left); 32 | if (node->right) 33 | stackNext.push(node->right); 34 | } 35 | else { 36 | if (node->right) 37 | stackNext.push(node->right); 38 | if (node->left) 39 | stackNext.push(node->left); 40 | } 41 | if (stackNow.empty()) { 42 | result.push_back(value); 43 | value.clear(); 44 | left2right = !left2right; 45 | swap(stackNow, stackNext); 46 | } 47 | } 48 | return move(result); 49 | } 50 | }; -------------------------------------------------------------------------------- /MinimumPathSum/MinimumPathSum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minPathSum(vector>& grid) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | 7 | int m = grid.size(); 8 | if (m == 0) return 0; 9 | int n = grid[0].size(); 10 | 11 | vector> dp(m, vector(n, 0)); 12 | 13 | dp[0][0] = grid[0][0]; 14 | for (int i = 1; i < m; i++) 15 | dp[i][0] = dp[i-1][0] + grid[i][0]; 16 | for (int j = 1; j < n; j++) 17 | dp[0][j] = dp[0][j-1] + grid[0][j]; 18 | 19 | for (int i = 1; i < m; i++) { 20 | for (int j = 1; j < n; j++) 21 | dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j]; 22 | } 23 | return dp[m-1][n-1]; 24 | } 25 | }; 26 | 27 | // O(n) space 28 | class Solution { 29 | public: 30 | int minPathSum(vector > &grid) { 31 | if (grid.empty()) { 32 | return 0; 33 | } 34 | int m = grid.size(); 35 | int n = grid[0].size(); 36 | vector> dp(2, vector(n, 0)); 37 | int T1 = 1; 38 | int T2 = 0; 39 | for (int i = 0; i < m; i++) { 40 | T1 ^= 1; 41 | T2 ^= 1; 42 | dp[T2][0] = dp[T1][0] + grid[i][0]; 43 | for (int j = 1; j < n; j++) { 44 | if (i == 0) { 45 | dp[T2][j] = dp[T2][j-1] + grid[i][j]; 46 | } else { 47 | dp[T2][j] = grid[i][j] + min(dp[T1][j], dp[T2][j-1]); 48 | } 49 | } 50 | } 51 | return dp[T2][n-1]; 52 | } 53 | }; 54 | -------------------------------------------------------------------------------- /LongestConsecutiveSequence/LongestConsecutiveSequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestConsecutive(vector &num) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | 7 | priority_queue Q; 8 | for (int i = 0; i < num.size(); i++) { 9 | Q.push(num[i]); 10 | } 11 | int ret = 1; 12 | int maxlen = 1; 13 | int temp = Q.top(); 14 | Q.pop(); 15 | while (!Q.empty()) { 16 | if (temp - 1 == Q.top()) { 17 | temp -= 1; 18 | maxlen += 1; 19 | } else if (temp != Q.top()) { 20 | temp = Q.top(); 21 | maxlen = 1; 22 | } 23 | Q.pop(); 24 | ret = max(maxlen, ret); 25 | } 26 | return ret; 27 | } 28 | }; 29 | 30 | // O(n) solution 31 | 32 | class Solution { 33 | public: 34 | int longestConsecutive(vector &num) { 35 | unordered_map longest; 36 | int result = 0; 37 | 38 | for (int i = 0; i < num.size(); i++) { 39 | if (longest[num[i]] != 0) { 40 | continue; 41 | } 42 | 43 | int leftbound = longest[num[i]-1]; 44 | int rightbound = longest[num[i]+1]; 45 | int bound = leftbound + rightbound + 1; 46 | 47 | longest[num[i]] = bound; 48 | longest[num[i]-leftbound] = bound; 49 | longest[num[i]+rightbound] = bound; 50 | 51 | if (result < bound) { 52 | result = bound; 53 | } 54 | } 55 | return result; 56 | } 57 | }; 58 | -------------------------------------------------------------------------------- /ReverseNodesink-Group/ReverseNodesink-Group.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode *reverseKGroup(ListNode *head, int k) { 12 | ListNode* node = head; 13 | int len = 0; 14 | while (node) { 15 | len++; 16 | node = node->next; 17 | } 18 | if (k > len) { 19 | return head; 20 | } 21 | 22 | ListNode prevhead(0); 23 | prevhead.next = head; 24 | 25 | ListNode* curr = head; 26 | ListNode* prev = &prevhead; 27 | 28 | while (curr) { 29 | int count = k - 1; 30 | ListNode* last = curr; 31 | while (count && last) { 32 | count--; 33 | last = last->next; 34 | } 35 | if (count == 0 && last) { 36 | ListNode* next = last->next; 37 | last->next = NULL; 38 | ListNode* l = reverse(curr); 39 | curr->next = next; 40 | prev->next = l; 41 | prev = curr; 42 | curr = next; 43 | } else { 44 | break; 45 | } 46 | } 47 | return prevhead.next; 48 | } 49 | 50 | ListNode* reverse(ListNode* head) { 51 | ListNode prevhead(0); 52 | while (head) { 53 | ListNode* next = head->next; 54 | head->next = prevhead.next; 55 | prevhead.next = head; 56 | head = next; 57 | } 58 | return prevhead.next; 59 | } 60 | }; 61 | -------------------------------------------------------------------------------- /AddTwoNumbers/AddTwoNumbers.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { 12 | // Start typing your C/C++ solution below 13 | // DO NOT write int main() function 14 | 15 | int carry = 0; 16 | ListNode *list = new ListNode(0); 17 | ListNode *head = list; 18 | ListNode *prev = list; 19 | while (l1 && l2) { 20 | carry += l1->val + l2->val; 21 | 22 | list = new ListNode(0); 23 | list->val = carry % 10; 24 | carry /= 10; 25 | 26 | l1 = l1->next; 27 | l2 = l2->next; 28 | prev->next = list; 29 | prev = prev->next; 30 | } 31 | while (l1) { 32 | carry += l1->val; 33 | 34 | list = new ListNode(0); 35 | list->val = carry % 10; 36 | carry /= 10; 37 | 38 | l1 = l1->next; 39 | prev->next = list; 40 | prev = prev->next; 41 | } 42 | while (l2) { 43 | carry += l2->val; 44 | 45 | list = new ListNode(0); 46 | list->val = carry % 10; 47 | carry /= 10; 48 | 49 | l2 = l2->next; 50 | prev->next = list; 51 | prev = prev->next; 52 | } 53 | if (carry) { 54 | list = new ListNode(0); 55 | list->val = carry; 56 | prev->next = list; 57 | prev = prev->next; 58 | } 59 | return head->next; 60 | } 61 | }; 62 | -------------------------------------------------------------------------------- /TrappingRainWater/TrappingRainWater.cpp: -------------------------------------------------------------------------------- 1 | // O(n) time, O(n) space 2 | class Solution { 3 | public: 4 | int trap(int A[], int n) { 5 | // Start typing your C/C++ solution below 6 | // DO NOT write int main() function 7 | 8 | int max_from_left[n]; 9 | int max_from_right[n]; 10 | 11 | max_from_left[0] = A[0]; 12 | for (int i = 1; i < n; i++) 13 | max_from_left[i] = max(max_from_left[i-1], A[i]); 14 | 15 | max_from_right[n-1] = A[n-1]; 16 | for (int i = n - 2; i >= 0; i--) 17 | max_from_right[i] = max(max_from_right[i+1], A[i]); 18 | 19 | int water = 0; 20 | for (int i = 1; i < n - 1; i++) { 21 | int min_height = min(max_from_left[i-1], max_from_right[i+1]); 22 | if (min_height > A[i]) 23 | water += min_height - A[i]; 24 | } 25 | return water; 26 | } 27 | }; 28 | 29 | // O(n) time, O(1) space 30 | class Solution { 31 | public: 32 | int trap(int A[], int n) { 33 | int maxh = 0; 34 | int water = 0; 35 | int temp = 0; 36 | for (int i = 0; i < n; i++) { 37 | if (A[i] <= maxh) { 38 | temp += maxh - A[i]; 39 | } else { 40 | maxh = A[i]; 41 | water += temp; 42 | temp = 0; 43 | } 44 | } 45 | maxh = 0; 46 | temp = 0; 47 | for (int i = n - 1; i >= 0; i--) { 48 | if (A[i] < maxh) { 49 | temp += maxh - A[i]; 50 | } else { 51 | maxh = A[i]; 52 | water += temp; 53 | temp = 0; 54 | } 55 | } 56 | return water; 57 | } 58 | }; 59 | -------------------------------------------------------------------------------- /PermutationsII/PermutationsII.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector > permuteUnique(vector &num) { 4 | vector> result; 5 | sort(num.begin(), num.end()); 6 | do { 7 | result.push_back(num); 8 | } while (getNext(num)); 9 | return result; 10 | } 11 | 12 | bool getNext(vector& num) { 13 | int i = num.size() - 1; 14 | while (i >= 1 && num[i-1] >= num[i]) { 15 | i--; 16 | } 17 | if (i == 0) { 18 | return false; 19 | } 20 | int j = num.size() - 1; 21 | while (j >= i) { 22 | if (num[j] > num[i-1]) { 23 | break; 24 | } 25 | j--; 26 | } 27 | swap(num[i-1], num[j]); 28 | reverse(num.begin() + i, num.end()); 29 | return true; 30 | } 31 | }; 32 | 33 | // recursive solution 34 | class Solution { 35 | public: 36 | void helper(vector>& result, vector& num, int x) { 37 | if (x == num.size()) { 38 | result.push_back(num); 39 | return; 40 | } 41 | helper(result, num, x + 1); 42 | map hash; 43 | hash[num[x]] = true; 44 | for (int i = x + 1; i < num.size(); i++) { 45 | if (hash[num[i]]) { 46 | continue; 47 | } 48 | hash[num[i]] = true; 49 | swap(num[x], num[i]); 50 | helper(result, num, x + 1); 51 | swap(num[x], num[i]); 52 | } 53 | } 54 | 55 | vector > permuteUnique(vector &num) { 56 | sort(num.begin(), num.end()); 57 | vector> result; 58 | helper(result, num, 0); 59 | return move(result); 60 | } 61 | }; 62 | -------------------------------------------------------------------------------- /ReverseWordsInAString/ReverseWordsInAString.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void reverseWords(string &s) { 4 | int i = 0; 5 | int j = s.size() - 1; 6 | 7 | while (i < s.size() && s[i] == ' ') { 8 | i++; 9 | } 10 | while (j >= 0 && s[j] == ' ') { 11 | j--; 12 | } 13 | 14 | s = s.substr(i, j - i + 1); 15 | reverse(s, 0, s.size() - 1); 16 | 17 | for (i = 0, j = 0; j < s.size(); j++) { 18 | if (s[j] == ' ') { 19 | s[i++] = ' '; 20 | while (j+1 < s.size() && s[j+1] == ' ') { 21 | j++; 22 | } 23 | } else { 24 | s[i++] = s[j]; 25 | } 26 | } 27 | s = s.substr(0, i); 28 | for (i = 0, j = 0; j < s.size(); j++) { 29 | if (s[j] == ' ') { 30 | reverse(s, i, j - 1); 31 | i = j + 1; 32 | } 33 | } 34 | 35 | if (i < s.size()) { 36 | reverse(s, i, s.size() - 1); 37 | } 38 | } 39 | 40 | void reverse(string& s, int i, int j) { 41 | while (i < j) { 42 | swap(s[i], s[j]); 43 | i++; 44 | j--; 45 | } 46 | } 47 | }; 48 | 49 | // solution 2 50 | class Solution { 51 | public: 52 | void reverseWords(string &s) { 53 | string result; 54 | for (int i = 0, start = 0; i < s.size(); i++) { 55 | if (s[i] == ' ') { 56 | if (i > start) { 57 | result = s.substr(start, i - start) + " " + result; 58 | } 59 | start = i + 1; 60 | } else if (i == s.size() - 1) { 61 | result = s.substr(start, i + 1 - start) + " " + result; 62 | } 63 | } 64 | s = result.substr(0, result.size() - 1); 65 | } 66 | }; 67 | -------------------------------------------------------------------------------- /MaximalRectangle/MaximalRectangle.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maximalRectangle(vector > &matrix) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | 7 | int row = matrix.size(); 8 | if (row == 0) return 0; 9 | int col = matrix[0].size(); 10 | 11 | int result = 0; 12 | int height[col]; 13 | memset(height, 0, sizeof(int)*col); 14 | 15 | for (int i = 0; i < row; i++) { 16 | for (int j = 0; j < col; j++) { 17 | if (matrix[i][j] == '1') 18 | height[j] += 1; 19 | else 20 | height[j] = 0; 21 | } 22 | int rect = getLargestRectInHistogram(height, col); 23 | result = max(result, rect); 24 | } 25 | return result; 26 | } 27 | 28 | int getLargestRectInHistogram(const int height[], int n) { 29 | int width[n]; 30 | stack minHeight; 31 | int result = 0; 32 | 33 | for (int i = 0; i < n; i++) { 34 | while (!minHeight.empty() && height[i] <= height[minHeight.top()]) 35 | minHeight.pop(); 36 | int left = minHeight.empty() ? -1 : minHeight.top(); 37 | width[i] = i - left - 1; 38 | minHeight.push(i); 39 | } 40 | 41 | while (!minHeight.empty()) 42 | minHeight.pop(); 43 | 44 | for (int i = n-1; i >= 0; i--) { 45 | while (!minHeight.empty() && height[i] <= height[minHeight.top()]) 46 | minHeight.pop(); 47 | int right = minHeight.empty() ? n : minHeight.top(); 48 | width[i] += right - i - 1; 49 | minHeight.push(i); 50 | } 51 | 52 | for (int i = 0; i < n; i++) { 53 | result = max(result, height[i] * (width[i] + 1)); 54 | } 55 | return result; 56 | } 57 | }; 58 | 59 | -------------------------------------------------------------------------------- /ValidNumber/ValidNumber.cpp: -------------------------------------------------------------------------------- 1 | // NFA 2 | class Solution { 3 | public: 4 | bool accept(const char* s, int& i, string expected) { 5 | for (int j = 0; j < expected.size(); j++) { 6 | if (s[i] == expected[j]) { 7 | i += 1; 8 | return true; 9 | } 10 | } 11 | return false; 12 | } 13 | 14 | bool acceptRun(const char* s, int& i, string expected) { 15 | bool found = false; 16 | int count = 0; 17 | while (s[i] != '\0') { 18 | found = false; 19 | for (int j = 0; j < expected.size(); j++) { 20 | if (s[i] == expected[j]) { 21 | i++; 22 | count++; 23 | found = true; 24 | } 25 | } 26 | if (!found) { 27 | break; 28 | } 29 | } 30 | if (count > 0) { 31 | return true; 32 | } 33 | return false; 34 | } 35 | 36 | bool isNumber(const char *s) { 37 | string digits("0123456789"); 38 | 39 | int i = 0; 40 | 41 | acceptRun(s, i, " "); 42 | 43 | bool beforedot = false; 44 | bool afterdot = false; 45 | 46 | accept(s, i, "+-"); 47 | beforedot = acceptRun(s, i, digits); 48 | 49 | if (accept(s, i, ".")) { 50 | if (acceptRun(s, i, digits)) { 51 | afterdot = true; 52 | } 53 | } 54 | 55 | if (!beforedot && !afterdot) { 56 | return false; 57 | } 58 | 59 | if (accept(s, i, "eE")) { 60 | accept(s, i, "+-"); 61 | if (!acceptRun(s, i, digits)) { 62 | return false; 63 | } 64 | } 65 | 66 | while (s[i] != '\0') { 67 | if (s[i] != ' ') { 68 | return false; 69 | } 70 | i++; 71 | } 72 | return true; 73 | } 74 | }; 75 | -------------------------------------------------------------------------------- /SudokuSolver/SudokuSolver.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool visited_cells[20][20]; 4 | bool visited_row[20][20]; 5 | bool visited_col[20][20]; 6 | 7 | void solveSudoku(vector>& board) { 8 | // Start typing your C/C++ solution below 9 | // DO NOT write int main() function 10 | 11 | memset(visited_cells, false, sizeof(visited_cells)); 12 | memset(visited_row, false, sizeof(visited_row)); 13 | memset(visited_col, false, sizeof(visited_col)); 14 | 15 | for (int i = 0; i < 9; i++) { 16 | for (int j = 0; j < 9; j++) { 17 | if (board[i][j] != '.') { 18 | int cell = (i / 3) * 3 + j / 3; 19 | int x = board[i][j] - '0'; 20 | visited_cells[cell][x] = true; 21 | visited_row[i][x] = visited_col[j][x] = true; 22 | } 23 | } 24 | } 25 | 26 | isValidSudokuHelper(board, 0); 27 | } 28 | 29 | bool isValidSudokuHelper(vector>& board, int step) { 30 | if (step == 81) return true; 31 | 32 | int row = step / 9; 33 | int col = step % 9; 34 | int cell = (row / 3) * 3 + col / 3; 35 | 36 | if (board[row][col] != '.') { 37 | return isValidSudokuHelper(board, step + 1); 38 | } 39 | for (int i = 1; i <= 9; i++) { 40 | if (!visited_cells[cell][i] && !visited_row[row][i] && !visited_col[col][i]) { 41 | visited_cells[cell][i] = true; 42 | visited_row[row][i] = visited_col[col][i] = true; 43 | board[row][col] = '0' + i; 44 | bool flag = isValidSudokuHelper(board, step + 1); 45 | if (flag) return true; 46 | board[row][col] = '.'; 47 | visited_cells[cell][i] = false; 48 | visited_row[row][i] = visited_col[col][i] = false; 49 | } 50 | } 51 | return false; 52 | } 53 | }; 54 | 55 | -------------------------------------------------------------------------------- /SortList/SortList.cc: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode *sortList(ListNode *head) { 12 | if (head == NULL || head->next == NULL) { 13 | return head; 14 | } 15 | 16 | ListNode new_head(0); 17 | new_head.next = head; 18 | 19 | ListNode* one = &new_head; 20 | ListNode* two = &new_head; 21 | 22 | while (two && two->next) { 23 | one = one->next; 24 | two = two->next->next; 25 | } 26 | 27 | ListNode* node = one->next; 28 | one->next = NULL; 29 | ListNode* left = sortList(new_head.next); 30 | ListNode* right = sortList(node); 31 | 32 | 33 | ListNode* sorted_head = NULL; 34 | ListNode* sorted_curr = NULL; 35 | 36 | if (left->val < right->val) { 37 | sorted_head = sorted_curr = left; 38 | left = left->next; 39 | } else { 40 | sorted_head = sorted_curr = right; 41 | right = right->next; 42 | } 43 | 44 | while (left && right) { 45 | if (left->val < right->val) { 46 | sorted_curr->next = left; 47 | sorted_curr = left; 48 | left = left->next; 49 | } else { 50 | sorted_curr->next = right; 51 | sorted_curr = right; 52 | right = right->next; 53 | } 54 | } 55 | 56 | while (left) { 57 | sorted_curr->next = left; 58 | sorted_curr = left; 59 | left = left->next; 60 | } 61 | while (right) { 62 | sorted_curr->next = right; 63 | sorted_curr = right; 64 | right = right->next; 65 | } 66 | 67 | sorted_curr->next = NULL; 68 | return sorted_head; 69 | } 70 | }; 71 | -------------------------------------------------------------------------------- /WordSearch/WordSearch.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool exist(vector>& board, string word) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | 7 | this->word = word; 8 | row = board.size(); 9 | if (row == 0) return false; 10 | col = board[0].size(); 11 | 12 | for (int i = 0; i < row; i++) { 13 | for (int j = 0; j < col; j++) { 14 | map[i][j] = board[i][j]; 15 | visited[i][j] = false; 16 | } 17 | } 18 | bool flag = false; 19 | for (int i = 0; i < row; i++) { 20 | for (int j = 0; j < col; j++) { 21 | if (map[i][j] == word[0]) { 22 | visited[i][j] = true; 23 | flag = DFS(i, j, 1); 24 | visited[i][j] = false; 25 | if (flag) return flag; 26 | } 27 | } 28 | } 29 | return false; 30 | } 31 | 32 | private: 33 | bool isValid(int x, int y) { 34 | if (0 <= x && x < row && 0 <= y && y < col) { 35 | return true; 36 | } 37 | return false; 38 | } 39 | 40 | bool DFS(int x, int y, int p) { 41 | if (p == word.size()) 42 | return true; 43 | 44 | bool flag = true; 45 | for (int i = 0; i < 4; i++) { 46 | int a = x + dx[i]; 47 | int b = y + dy[i]; 48 | if (isValid(a, b) && !visited[a][b] && map[a][b] == word[p]) { 49 | visited[a][b] = true; 50 | flag = DFS(a, b, p + 1); 51 | visited[a][b] = false; 52 | if (flag) return true; 53 | } 54 | } 55 | return false; 56 | } 57 | 58 | private: 59 | static const int MAXN = 1010; 60 | int dx[4] = {1, -1, 0, 0}; 61 | int dy[4] = {0, 0, -1, 1}; 62 | int row, col; 63 | // 56ms judge large 64 | // much faster than pass-by-reference 65 | char map[MAXN][MAXN]; 66 | bool visited[MAXN][MAXN]; 67 | string word; 68 | }; -------------------------------------------------------------------------------- /BinaryTreeInorderTraversal/BinaryTreeInorderTraversal.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | vector inorderTraversal(TreeNode *root) { 13 | // Start typing your C/C++ solution below 14 | // DO NOT write int main() function 15 | 16 | vector inorder; 17 | stack tree_stack; 18 | TreeNode *node = root; 19 | 20 | while (node || !tree_stack.empty()) { 21 | while (node) { 22 | tree_stack.push(node); 23 | node = node->left; 24 | } 25 | if (!tree_stack.empty()) { 26 | node = tree_stack.top(); 27 | tree_stack.pop(); 28 | inorder.push_back(node->val); 29 | node = node->right; 30 | } 31 | } 32 | return inorder; 33 | } 34 | }; 35 | 36 | // solution 2, O(1) space 37 | class Solution { 38 | public: 39 | vector inorderTraversal(TreeNode *root) { 40 | // Start typing your C/C++ solution below 41 | // DO NOT write int main() function 42 | 43 | vector inorder; 44 | TreeNode *current = root; 45 | 46 | while (current != NULL) { 47 | if (current->left == NULL) { 48 | inorder.push_back(current->val); 49 | current = current->right; 50 | } 51 | else { 52 | TreeNode *prev = current->left; 53 | while (prev->right && prev->right != current) 54 | prev = prev->right; 55 | if (prev->right == NULL) { 56 | prev->right = current; 57 | current = current->left; 58 | } 59 | else { 60 | inorder.push_back(current->val); 61 | prev->right = NULL; 62 | current = current->right; 63 | } 64 | } 65 | } 66 | return inorder; 67 | } 68 | }; -------------------------------------------------------------------------------- /MaxPointsOnALine/MaxPointsOnALine.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a point. 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 | 11 | bool operator<(const Point& x, const Point& y) { 12 | if (x.x == y.x) { 13 | return x.y < y.y; 14 | } 15 | return x.x < y.x; 16 | } 17 | 18 | bool operator==(const Point& x, const Point& y) { 19 | if (x.x == y.x && x.y == y.y) { 20 | return true; 21 | } 22 | return false; 23 | } 24 | 25 | class Solution { 26 | public: 27 | int maxPoints(vector &points) { 28 | int n = points.size(); 29 | if (n <= 2) { 30 | return n; 31 | } 32 | int result = 2; 33 | sort(points.begin(), points.end()); 34 | for (int i = 0; i < n; i++) { 35 | vector> slopes; 36 | int count = 0; 37 | for (int j = i + 1; j < n; j++) { 38 | int x = points[i].x - points[j].x; 39 | int y = points[i].y - points[j].y; 40 | int z = gcd(x, y); 41 | if (z != 0) { 42 | x /= z, y /= z; 43 | } 44 | if (x == 0 && y == 0) { 45 | count++; 46 | } else { 47 | slopes.push_back(make_pair(x, y)); 48 | } 49 | } 50 | if (slopes.empty()) { 51 | result = max(result, count + 1); 52 | continue; 53 | } 54 | sort(slopes.begin(), slopes.end()); 55 | int curr = 2 + count; 56 | result = max(result, curr); 57 | for (int j = 1; j < slopes.size(); j++) { 58 | if (slopes[j] == slopes[j-1]) { 59 | curr++; 60 | } else { 61 | curr = 2 + count; 62 | } 63 | result = max(result, curr); 64 | } 65 | } 66 | return result; 67 | } 68 | 69 | int gcd(int a, int b) { 70 | while (b != 0) { 71 | int t = b; 72 | b = a % b; 73 | a = t; 74 | } 75 | return a; 76 | } 77 | }; 78 | -------------------------------------------------------------------------------- /FlattenBinaryTreetoLinkedList/FlattenBinaryTreetoLinkedList.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | void flatten(TreeNode *root) { 13 | // Start typing your C/C++ solution below 14 | // DO NOT write int main() function 15 | 16 | if (root == NULL) return; 17 | 18 | stack tree_stack; 19 | TreeNode *flatten_node = NULL; 20 | tree_stack.push(root); 21 | 22 | while (!tree_stack.empty()) { 23 | TreeNode *node = tree_stack.top(); 24 | tree_stack.pop(); 25 | if (node->right) { 26 | tree_stack.push(node->right); 27 | node->right = NULL; 28 | } 29 | if (node->left) { 30 | tree_stack.push(node->left); 31 | node->left = NULL; 32 | } 33 | if (flatten_node == NULL) { 34 | flatten_node = node; 35 | } else { 36 | flatten_node->right = node; 37 | flatten_node = flatten_node->right; 38 | } 39 | } 40 | } 41 | }; 42 | 43 | // recursion 44 | class Solution { 45 | public: 46 | void flatten(TreeNode *root) { 47 | dfs(root); 48 | } 49 | 50 | pair dfs(TreeNode* root) { 51 | if (root == NULL) { 52 | return make_pair((TreeNode*)NULL, (TreeNode*)NULL); 53 | } 54 | pair left = dfs(root->left); 55 | pair right = dfs(root->right); 56 | root->left = NULL; 57 | root->right = NULL; 58 | if (left.first && right.first) { 59 | root->right = left.first; 60 | left.second->right = right.first; 61 | return make_pair(root, right.second); 62 | } else if (left.first) { 63 | root->right = left.first; 64 | return make_pair(root, left.second); 65 | } else if (right.first) { 66 | root->right = right.first; 67 | return make_pair(root, right.second); 68 | } 69 | return make_pair(root, root); 70 | } 71 | }; 72 | -------------------------------------------------------------------------------- /TextJustification/TextJustification.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector fullJustify(vector& words, int L) { 4 | // Start typing your C/C++ solution below 5 | // DO NOT write int main() function 6 | 7 | vector needed_lines(words.size(), 0); 8 | int count_line = 1; 9 | int len = 0; 10 | for (int i = 0; i < words.size(); i++) { 11 | if (len + words[i].size() + 1 <= L + 1) { 12 | needed_lines[i] = count_line; 13 | len += words[i].size() + 1; 14 | } 15 | else { 16 | count_line += 1; 17 | len = words[i].size() + 1; 18 | needed_lines[i] = count_line; 19 | } 20 | } 21 | vector justified; 22 | int start = 0; 23 | 24 | while (start < words.size()) { 25 | int end = start + 1; 26 | int words_len = words[start].size(); 27 | while (end < words.size() && needed_lines[start] == needed_lines[end]) { 28 | words_len += words[end].size(); 29 | end += 1; 30 | } 31 | int words_num = end - start; 32 | string justified_line; 33 | if (words_num == 1) { 34 | justified_line += words[start]; 35 | justified_line.append(L - words_len, ' '); 36 | } 37 | else { 38 | int extra = (L - words_len) % (words_num - 1); 39 | int blank = (L - words_len) / (words_num - 1); 40 | if (end == words.size()) { 41 | extra = 0; blank = 1; 42 | } 43 | for (int i = start; i < end; i++) { 44 | justified_line += words[i]; 45 | if (i == end -1) continue; 46 | if (extra > 0) { 47 | justified_line.append(blank + 1, ' '); 48 | extra -= 1; 49 | } 50 | else 51 | justified_line.append(blank, ' '); 52 | } 53 | if (end == words.size()) { 54 | justified_line.append(L - words_len - words_num + 1, ' '); 55 | } 56 | } 57 | justified.push_back(justified_line); 58 | start = end; 59 | } 60 | return justified; 61 | } 62 | }; -------------------------------------------------------------------------------- /ValidateBinarySearchTree/ValidateBinarySearchTree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | bool isValidBST(TreeNode *root) { 13 | if (root == NULL) 14 | return true; 15 | 16 | return valid(root->left, INT_MIN, root->val) && 17 | valid(root->right, root->val, INT_MAX); 18 | } 19 | 20 | bool valid(TreeNode *node, int start, int limit) { 21 | if (node == NULL) 22 | return true; 23 | 24 | if (node->val >= limit || node->val <= start) 25 | return false; 26 | 27 | return valid(node->left, start, node->val) && 28 | valid(node->right, node->val, limit); 29 | } 30 | }; 31 | 32 | // 33 | // Solution 2, O(1) space 34 | // 35 | class Solution { 36 | public: 37 | bool isValidBST(TreeNode *root) { 38 | // Start typing your C/C++ solution below 39 | // DO NOT write int main() function 40 | 41 | TreeNode *parent = NULL; 42 | TreeNode *current = root; 43 | bool flag = true; 44 | 45 | while (current != NULL) { 46 | if (current->left == NULL) { 47 | if (parent && parent->val >= current->val) 48 | flag = false; 49 | 50 | parent = current; 51 | current = current->right; 52 | } 53 | else { 54 | TreeNode *left_right_most = current->left; 55 | while (left_right_most->right && left_right_most->right != current) 56 | left_right_most = left_right_most->right; 57 | 58 | if (left_right_most->right == NULL) { 59 | left_right_most->right = current; 60 | current = current->left; 61 | } 62 | else { 63 | if (parent && parent->val >= current->val) 64 | flag = false; 65 | 66 | left_right_most->right = NULL; 67 | parent = current; 68 | current = current->right; 69 | } 70 | } 71 | } 72 | return flag; 73 | } 74 | }; 75 | // http://fisherlei.blogspot.com/2012/12/leetcode-recover-binary-search-tree.html 76 | -------------------------------------------------------------------------------- /4Sum/4Sum.cpp: -------------------------------------------------------------------------------- 1 | 2 | struct twoSum { 3 | int lf, rt, val; 4 | twoSum(int _lf, int _rt, int _val) 5 | : lf(_lf), rt(_rt), val(_val) { } 6 | friend bool operator < (const twoSum& lhs, const twoSum& rhs) { 7 | return lhs.val < rhs.val; 8 | } 9 | }; 10 | 11 | class Solution { 12 | public: 13 | vector> fourSum(vector& num, int target) { 14 | // Start typing your C/C++ solution below 15 | // DO NOT write int main() function 16 | vector> result; 17 | vector twosums; 18 | for (int i = 0; i < num.size(); i++) { 19 | for (int j = i + 1; j < num.size(); j++) 20 | twosums.push_back(twoSum(i, j, num[i]+num[j])); 21 | } 22 | sort(twosums.begin(), twosums.end()); 23 | 24 | int n = twosums.size(); 25 | for (int i = 0; i < n; i++) { 26 | int value = target - twosums[i].val; 27 | int lf = find_lower_bound(twosums, i + 1, n - 1, value); 28 | int rt = find_upper_bound(twosums, i + 1, n - 1, value); 29 | for (int j = lf; j <= rt; j++) { 30 | if (twosums[i].lf == twosums[j].lf) continue; 31 | if (twosums[i].rt == twosums[j].lf) continue; 32 | if (twosums[i].lf == twosums[j].rt) continue; 33 | if (twosums[i].rt == twosums[j].rt) continue; 34 | vector four; 35 | four.push_back(num[twosums[i].lf]); 36 | four.push_back(num[twosums[i].rt]); 37 | four.push_back(num[twosums[j].lf]); 38 | four.push_back(num[twosums[j].rt]); 39 | sort(four.begin(), four.end()); 40 | if (find(result.begin(), result.end(), four) == result.end()) 41 | result.push_back(four); 42 | } 43 | } 44 | return move(result); 45 | } 46 | int find_lower_bound(vector& twosums, int l, int r, int val) { 47 | while (l <= r) { 48 | int m = (l + r) / 2; 49 | if (twosums[m].val >= val) 50 | r = m - 1; 51 | else 52 | l = m + 1; 53 | } 54 | return r + 1; 55 | } 56 | int find_upper_bound(vector& twosums, int l, int r, int val) { 57 | while (l <= r) { 58 | int m = (l + r) / 2; 59 | if (twosums[m].val <= val) 60 | l = m + 1; 61 | else 62 | r = m - 1; 63 | } 64 | return l - 1; 65 | } 66 | }; -------------------------------------------------------------------------------- /WordLadderII/WordLadderII.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | vector vdict; 4 | vector> map; 5 | vector> prev; 6 | 7 | void buildMap(const unordered_set& dict) { 8 | vdict.clear(); 9 | unordered_map unmap; 10 | for (auto iter = dict.begin(); iter != dict.end(); iter++) { 11 | unmap[*iter] = vdict.size(); 12 | vdict.push_back(*iter); 13 | } 14 | 15 | map.clear(); 16 | map.resize(vdict.size()); 17 | for (size_t i = 0; i < vdict.size(); i++) { 18 | string word = vdict[i]; 19 | for (size_t j = 0; j < word.size(); j++) { 20 | for (char c = 'a'; c <= 'z'; c++) { 21 | if (c == vdict[i][j]) continue; 22 | word[j] = c; 23 | if (unmap.count(word)) { 24 | map[i].push_back(unmap[word]); 25 | } 26 | word[j] = vdict[i][j]; 27 | } 28 | } 29 | } 30 | } 31 | 32 | void buildReverseMap(int src, int dst) { 33 | prev.clear(); 34 | prev.resize(vdict.size()); 35 | vector dist(vdict.size()); 36 | queue Q; 37 | Q.push(src); 38 | dist[src] = 0; 39 | while (!Q.empty()) { 40 | src = Q.front(); Q.pop(); 41 | if (src == dst) break; 42 | for (size_t i = 0; i < map[src].size(); i++) { 43 | int v = map[src][i]; 44 | if (prev[v].size() == 0) { 45 | prev[v].push_back(src); 46 | dist[v] = dist[src] + 1; 47 | Q.push(v); 48 | } else if (dist[v] == dist[src] + 1) { 49 | prev[v].push_back(src); 50 | } 51 | } 52 | } 53 | } 54 | 55 | void dfs(int u, int v, vector& path, vector>& result) { 56 | path.push_back(v); 57 | if (u == v && path.size()) { 58 | vector pathstring; 59 | for (auto iter = path.rbegin(); iter != path.rend(); iter++) { 60 | pathstring.push_back(vdict[*iter]); 61 | } 62 | result.push_back(pathstring); 63 | } else { 64 | for (size_t i = 0; i < prev[v].size(); i++) 65 | dfs(u, prev[v][i], path, result); 66 | } 67 | path.pop_back(); 68 | } 69 | 70 | public: 71 | vector> findLadders(string start, string end, unordered_set &dict) { 72 | // Start typing your C/C++ solution below 73 | // DO NOT write int main() function 74 | dict.insert(start); 75 | dict.insert(end); 76 | 77 | buildMap(dict); 78 | 79 | int src, dst; 80 | for (src = 0; start != vdict[src]; src++); 81 | for (dst = 0; end != vdict[dst]; dst++); 82 | 83 | buildReverseMap(src, dst); 84 | 85 | vector> result; 86 | vector path; 87 | dfs(src, dst, path, result); 88 | return move(result); 89 | } 90 | }; 91 | --------------------------------------------------------------------------------