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