Full Code of kedebug/leetcode for AI

master daad6499a416 cached
144 files
140.0 KB
42.1k tokens
372 symbols
1 requests
Download .txt
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<vector<int> > threeSum(vector<int> &num) {
        vector<vector<int>> 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<int> 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<int> &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<vector<int>> fourSum(vector<int>& num, int target) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<vector<int>> result;
        vector<twoSum> 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<int> 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<twoSum>& 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<twoSum>& 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<string> anagrams(vector<string> &strs) {
        vector<string> result;
        map<string, int> 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<int> &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<int>& 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<int> &prices) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (prices.empty()) return 0;

        vector<int> 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<int> &prices) {
        if (prices.size() < 2) {
            return 0;
        }
        int n = prices.size();
        vector<int> dp1(n, 0);
        vector<int> 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<int> inorderTraversal(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        vector<int> inorder;
        stack<TreeNode*> 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<int> inorderTraversal(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        vector<int> 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<vector<int> > levelOrder(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        vector<vector<int>> result;
        if (root == NULL) return result;
        
        queue<TreeNode*> nodeQueue;
        vector<int> 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<vector<int> > levelOrderBottom(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        vector<vector<int>> result;
        if (root == NULL) return result;
        
        queue<TreeNode*> nodeQueue;
        vector<int> 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<int>& result, TreeNode* from, TreeNode* to) {
        vector<int> 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<int> postorderTraversal(TreeNode *root) {
        vector<int> 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<int> preorderTraversal(TreeNode *root) {
        vector<int> 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<vector<int>> zigzagLevelOrder(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        vector<vector<int>> result;
        if (root == NULL) return result;
        
        stack<TreeNode*> stackNow;
        stack<TreeNode*> stackNext;
        vector<int> 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<UndirectedGraphNode *> neighbors;
 *     UndirectedGraphNode(int x) : label(x) {};
 * };
 */
class Solution {
public:
    UndirectedGraphNode* clone(UndirectedGraphNode* node, map<UndirectedGraphNode*, UndirectedGraphNode*>& 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<UndirectedGraphNode*, UndirectedGraphNode*> graph;
        return clone(node, graph);
    }
};


================================================
FILE: CombinationSum/CombinationSum.cpp
================================================
class Solution {
public:
    vector<vector<int> > combinationSum(vector<int> &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<int> nums;
        DFS(nums, target, candidates, 0);
        return move(combination_set);
    }
    
    void DFS(vector<int>& nums, int target, vector<int>& 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<vector<int>> combination_set;
};

================================================
FILE: CombinationSumII/CombinationSumII.cpp
================================================
class Solution {
public:
    vector<vector<int>> combinationSum2(vector<int>& 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<int> nums;
        DFS(nums, target, candidates, 0);
        return move(combination_set);
    }
    
    void DFS(vector<int>& nums, int target, vector<int>& 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<vector<int>> combination_set;
};

================================================
FILE: Combinations/Combinations.cpp
================================================
class Solution {
public:
    vector<vector<int> > combine(int n, int k) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        vector<vector<int>> result;
        vector<int> comb;
        DFS(comb, 0, 0, k, n, result);
        return move(result);
    }
    
    void DFS(vector<int>& comb, int step, int p, int k, int n, vector<vector<int>>& 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<int> &inorder, vector<int> &postorder) {
        if (inorder.empty()) {
            return NULL;
        }
        return dfs(inorder, 0, inorder.size() - 1, postorder, 0, postorder.size() - 1);
    }
    TreeNode* dfs(vector<int>& inorder, int l1, int r1, vector<int>& 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<int> &preorder, vector<int> &inorder) {
        if (preorder.size() == 0) {
            return NULL;
        }
        return dfs(preorder, 0, preorder.size() - 1, inorder, 0, inorder.size() - 1);
    }
    
    TreeNode* dfs(vector<int>& preorder, int l1, int r1, vector<int>& 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<int>& 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<int> &num) {
        return dfs(num, 0, num.size() - 1);
    }
    TreeNode* dfs(vector<int>& 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<int> 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<vector<int>> dp(word1.size() + 1, vector<int>(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<string> &tokens) {
        stack<int> nums;
        stack<char> 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<TreeNode*> 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<TreeNode*, TreeNode*> dfs(TreeNode* root) {
        if (root == NULL) {
            return make_pair((TreeNode*)NULL, (TreeNode*)NULL);
        }
        pair<TreeNode*, TreeNode*> left = dfs(root->left);
        pair<TreeNode*, TreeNode*> 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<string> generateParenthesis(int n) {
        vector<string> result;
        string s;
        if (n == 0) {
            return result;
        }
        dfs(result, s, n, n);
        return result;
    }
    void dfs(vector<string>& 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<int> grayCode(int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        vector<int> 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<int> grayCode(int n) {
        vector<int> 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<int> 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<Interval> insert(vector<Interval> &intervals, Interval newInterval) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        vector<Interval> 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<vector<bool>> dp(2, vector<bool>(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<int, entry*> cache_;
    struct entry dummy_;
};


================================================
FILE: LargestRectangleinHistogram/LargestRectangleinHistogram.cpp
================================================
class Solution {
public:
    int largestRectangleArea(vector<int>& height) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        int n = height.size();
        int width[n];
        stack<int> 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<string> letterCombinations(string digits) {
        map<int, string> 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<string> result;
        string letter;
        dfs(result, letter, digits, 0, keypad);
        return result;
    }
    void dfs(vector<string>& result, string& letter, string& digits, int pos, map<int, string>& 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<string> &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<int> &num) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        priority_queue<int> 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<int> &num) {
        unordered_map<int, int> 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<Point> &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<pair<int, int>> 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<vector<char> > &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<int> 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<Interval> merge(vector<Interval> &intervals) {
        vector<Interval> 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<ListNode *> &lists) {
        return merge(lists, 0, lists.size() - 1);
    }
    ListNode* merge(vector<ListNode*>& 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<vector<int>>& 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<vector<int>> dp(m, vector<int>(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<vector<int> > &grid) {
        if (grid.empty()) {
            return 0;
        }
        int m = grid.size();
        int n = grid[0].size();
        vector<vector<int>> dp(2, vector<int>(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<char, int> needed;
        map<char, int> 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<int> 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<vector<string> > solveNQueens(int n) {
        vector<vector<string>> result;
        if (n == 0) {
            return result;
        }
        vector<string> sol(n, string(n, '.'));
        vector<vector<bool>> visited(3, vector<bool>(2*n, false));
        dfs(result, sol, visited, 0);
        return result;
    }
    
    void dfs(vector<vector<string>>& result, vector<string>& sol,  vector<vector<bool>>& 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<int> &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<vector<string> > partition(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        ans.clear();
        dynamic(s);
        vector<string> v;
        dfs(s, 0, v);
        return ans;

    }
    void dfs(string& s, int p, vector<string>& 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<vector<string> > 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<vector<int> > generate(int numRows) {
        vector<vector<int>> triangle;
        if (numRows == 0) {
            return triangle;
        }
        triangle.push_back(vector<int>(1, 1));
        for (int i = 1; i < numRows; i++) {
            vector<int>& prev = triangle.back();
            vector<int> 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<int> getRow(int rowIndex) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        vector<int> 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<vector<int> > pathSum(TreeNode *root, int sum) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<vector<int>> result;
        vector<int> path;
        dfs(root, 0, sum, path, result);
        return move(result);
        
    }
    void dfs(TreeNode *node, int value, int sum, 
        vector<int>& path, vector<vector<int>>& 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<vector<int>> permute(vector<int>& num) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        vector<vector<int>> result;
        dfs(num, 0, result);
        return move(result);
    }
    
    void dfs(vector<int>& num, int step, vector<vector<int>>& 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<vector<int> > permuteUnique(vector<int> &num) {
        vector<vector<int>> result;
        sort(num.begin(), num.end());
        do {
            result.push_back(num);
        } while (getNext(num));
        return result;
    }
    
    bool getNext(vector<int>& 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<vector<int>>& result, vector<int>& num, int x) {
        if (x == num.size()) {
            result.push_back(num);
            return;
        }
        helper(result, num, x + 1);
        map<int, bool> 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<vector<int> > permuteUnique(vector<int> &num) {
        sort(num.begin(), num.end());
        vector<vector<int>> result;
        helper(result, num, 0);
        return move(result);
    }
};


================================================
FILE: PlusOne/PlusOne.cpp
================================================
class Solution {
public:
    vector<int> plusOne(vector<int>& 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<string> restoreIpAddresses(string s) {
        vector<string> result;
        vector<int> sk;
        dfs(result, sk, s, 0, 0);
        return result;
    }
    
    void dfs(vector<string>& result, vector<int>& 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<vector<int>>& 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<vector<int>>& 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<int>& 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<int> searchRange(int A[], int n, int target) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        vector<int> 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<vector<int>>& 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<string> 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<int> spiralOrder(vector<vector<int> > &matrix) {
        vector<int> 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<vector<int> > generateMatrix(int n) {
        vector<vector<int>> matrix(n, vector<int>(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<vector<int> > subsets(vector<int>& S) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        vector<vector<int>> result;
        vector<int> subset;
        
        sort(S.begin(), S.end());
        DFS(subset, 0, S, result);
        return move(result);
    }
    
    void DFS(vector<int>& subset, int step, vector<int>& S, vector<vector<int>>& 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<vector<int>> subsetsWithDup(vector<int>& S) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        
        vector<vector<int>> subsets;
        vector<int> integers;
        
        if (S.empty()) return subsets;
        
        sort(S.begin(), S.end());
        DFS(integers, 0, S, subsets);
        
        return move(subsets);
    }
    
    void DFS(vector<int>& integers, int start, vector<int>& S, vector<vector<int>>& 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<int> findSubstring(string S, vector<string> &L) {
        vector<int> result;
        if (L.empty()) {
            return result;
        }
        int n = L.size();
        int len = L[0].size();
        map<string, int> hash;
        for (int i = 0; i < n; i++) {
            hash[L[i]] += 1;
        }
        for (int i = 0; i < len; i++) {
            vector<string> 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<string, int> 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<vector<char>>& 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<vector<char>>& 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<vector<char>> &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<vector<char>> &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<TreeNode*> 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<string> fullJustify(vector<string>& words, int L) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        vector<int> 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<string> 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<vector<int> > &triangle) {
        int level = triangle.size();
        vector<int> 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<int, int>& lhs, const pair<int, int>& rhs) {
    if (lhs.first == rhs.first) 
        return lhs.second < rhs.second;
    return lhs.first < rhs.first;
}

class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        vector<pair<int, int>> 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<int> 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<int> 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<TreeNode *> generateTrees(int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        return generateTreesHelper(1, n);
    }
    
    vector<TreeNode *> generateTreesHelper(int left, int right) {
        vector<TreeNode *> trees;
        if (left > right) {
            trees.push_back(NULL);
            return trees;
        }
        for (int r = left; r <= right; r++) {
            vector<TreeNode *> left_trees = generateTreesHelper(left, r - 1);
            vector<TreeNode *> 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<vector<int>> dp(m, vector<int>(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<vector<int>>& 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<vector<int>> dp(m, vector<int>(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<vector<char>> &board) {
        vector<vector<bool>> rows(9, vector<bool>(9, false));
        vector<vector<bool>> cols(9, vector<bool>(9, false));
        vector<vector<bool>> cells(9, vector<bool>(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<string> &dict) {
        queue<string> q;
        unordered_map<string, bool> visited;
        map<string, string> 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<string> vdict;
    vector<vector<int>> map;
    vector<vector<int>> prev;

    void buildMap(const unordered_set<string>& dict) {
        vdict.clear();
        unordered_map<string, int> 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<int> dist(vdict.size());
        queue<int> 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<int>& path, vector<vector<string>>& result) {
        path.push_back(v);
        if (u == v && path.size()) {
            vector<string> 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<vector<string>> findLadders(string start, string end, unordered_set<string> &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<vector<string>> result;
        vector<int> path;
        dfs(src, dst, path, result);
        return move(result);
    }
};


================================================
FILE: WordSearch/WordSearch.cpp
================================================
class Solution {
public:
    bool exist(vector<vector<char>>& 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;
    }
};
Download .txt
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
Download .txt
SYMBOL INDEX (372 symbols across 142 files)

FILE: 3Sum/3Sum.cpp
  class Solution (line 1) | class Solution {
    method threeSum (line 3) | vector<vector<int> > threeSum(vector<int> &num) {

FILE: 3SumClosest/3SumClosest.cpp
  class Solution (line 1) | class Solution {
    method threeSumClosest (line 3) | int threeSumClosest(vector<int> &num, int target) {

FILE: 4Sum/4Sum.cpp
  type twoSum (line 2) | struct twoSum {
    method twoSum (line 4) | twoSum(int _lf, int _rt, int _val)
  class Solution (line 11) | class Solution {
    method fourSum (line 13) | vector<vector<int>> fourSum(vector<int>& num, int target) {
    method find_lower_bound (line 46) | int find_lower_bound(vector<twoSum>& twosums, int l, int r, int val) {
    method find_upper_bound (line 56) | int find_upper_bound(vector<twoSum>& twosums, int l, int r, int val) {

FILE: AddBinary/AddBinary.cpp
  class Solution (line 1) | class Solution {
    method string (line 3) | string addBinary(string a, string b) {

FILE: AddTwoNumbers/AddTwoNumbers.cpp
  class Solution (line 9) | class Solution {
    method ListNode (line 11) | ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {

FILE: Anagrams/Anagrams.cpp
  class Solution (line 1) | class Solution {
    method anagrams (line 3) | vector<string> anagrams(vector<string> &strs) {

FILE: BalancedBinaryTree/BalancedBinaryTree.cpp
  class Solution (line 10) | class Solution {
    method isBalanced (line 12) | bool isBalanced(TreeNode *root) {
    method dfs (line 19) | int dfs(TreeNode* node, bool& flag) {

FILE: BestTimetoBuyandSellStock/BestTimetoBuyandSellStock.cpp
  class Solution (line 1) | class Solution {
    method maxProfit (line 3) | int maxProfit(vector<int> &prices) {

FILE: BestTimetoBuyandSellStockII/BestTimetoBuyandSellStockII.cpp
  class Solution (line 1) | class Solution {
    method maxProfit (line 3) | int maxProfit(vector<int>& prices) {
    method maxProfit2 (line 24) | int maxProfit2(vector<int> &prices) {

FILE: BestTimetoBuyandSellStockIII/BestTimetoBuyandSellStockIII.cpp
  class Solution (line 1) | class Solution {
    method maxProfit (line 3) | int maxProfit(vector<int> &prices) {

FILE: BinaryTreeInorderTraversal/BinaryTreeInorderTraversal.cpp
  class Solution (line 10) | class Solution {
    method inorderTraversal (line 12) | vector<int> inorderTraversal(TreeNode *root) {
    method inorderTraversal (line 39) | vector<int> inorderTraversal(TreeNode *root) {
  class Solution (line 37) | class Solution {
    method inorderTraversal (line 12) | vector<int> inorderTraversal(TreeNode *root) {
    method inorderTraversal (line 39) | vector<int> inorderTraversal(TreeNode *root) {

FILE: BinaryTreeLevelOrderTraversal/BinaryTreeLevelOrderTraversal.cpp
  class Solution (line 10) | class Solution {
    method levelOrder (line 12) | vector<vector<int> > levelOrder(TreeNode *root) {

FILE: BinaryTreeLevelOrderTraversalII/BinaryTreeLevelOrderTraversalII.cpp
  class Solution (line 10) | class Solution {
    method levelOrderBottom (line 12) | vector<vector<int> > levelOrderBottom(TreeNode *root) {

FILE: BinaryTreeMaximumPathSum/BinaryTreeMaximumPathSum.cpp
  class Solution (line 10) | class Solution {
    method maxPathSum (line 12) | int maxPathSum(TreeNode *root) {
    method dfs (line 21) | int dfs(TreeNode* node, int* maxsum) {

FILE: BinaryTreePostorderTraversal/BinaryTreePostorderTraversal.cc
  class Solution (line 10) | class Solution {
    method print (line 12) | void print(vector<int>& result, TreeNode* from, TreeNode* to) {
    method postorderTraversal (line 26) | vector<int> postorderTraversal(TreeNode *root) {

FILE: BinaryTreePreorderTraversal/BinaryTreePreorderTraversal.cpp
  class Solution (line 10) | class Solution {
    method preorderTraversal (line 12) | vector<int> preorderTraversal(TreeNode *root) {

FILE: BinaryTreeZigzagLevelOrderTraversal/BinaryTreeZigzagLevelOrderTraversal.cpp
  class Solution (line 10) | class Solution {
    method zigzagLevelOrder (line 12) | vector<vector<int>> zigzagLevelOrder(TreeNode *root) {

FILE: ClimbingStairs/ClimbingStairs.cpp
  class Matrix (line 3) | class Matrix {
    method Matrix (line 7) | Matrix() {}
    method Matrix (line 8) | Matrix(int _x00, int _x01, int _x10, int _x11)
    method Matrix (line 10) | Matrix operator * (const Matrix& o) {
  class Solution (line 20) | class Solution {
    method climbStairs (line 22) | int climbStairs(int n) {

FILE: CloneGraph/CloneGraph.cc
  class Solution (line 9) | class Solution {
    method UndirectedGraphNode (line 11) | UndirectedGraphNode* clone(UndirectedGraphNode* node, map<UndirectedGr...
    method UndirectedGraphNode (line 27) | UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {

FILE: CombinationSum/CombinationSum.cpp
  class Solution (line 1) | class Solution {
    method combinationSum (line 3) | vector<vector<int> > combinationSum(vector<int> &candidates, int targe...
    method DFS (line 14) | void DFS(vector<int>& nums, int target, vector<int>& candidates, int p...

FILE: CombinationSumII/CombinationSumII.cpp
  class Solution (line 1) | class Solution {
    method combinationSum2 (line 3) | vector<vector<int>> combinationSum2(vector<int>& candidates, int targe...
    method DFS (line 14) | void DFS(vector<int>& nums, int target, vector<int>& candidates, int p...

FILE: Combinations/Combinations.cpp
  class Solution (line 1) | class Solution {
    method combine (line 3) | vector<vector<int> > combine(int n, int k) {
    method DFS (line 13) | void DFS(vector<int>& comb, int step, int p, int k, int n, vector<vect...

FILE: ConstructBinaryTreefromInorderandPostorderTraversal/ConstructBinaryTreefromInorderandPostorderTraversal.cpp
  class Solution (line 10) | class Solution {
    method TreeNode (line 12) | TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
    method TreeNode (line 18) | TreeNode* dfs(vector<int>& inorder, int l1, int r1, vector<int>& posto...

FILE: ConstructBinaryTreefromPreorderandInorderTraversal/ConstructBinaryTreefromPreorderandInorderTraversal.cpp
  class Solution (line 10) | class Solution {
    method TreeNode (line 12) | TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
    method TreeNode (line 19) | TreeNode* dfs(vector<int>& preorder, int l1, int r1, vector<int>& inor...

FILE: ContainerWithMostWater/ContainerWithMostWater.cpp
  class Solution (line 1) | class Solution {
    method maxArea (line 3) | int maxArea(vector<int>& height) {

FILE: ConvertSortedArraytoBinarySearchTree/ConvertSortedArraytoBinarySearchTree.cpp
  class Solution (line 10) | class Solution {
    method TreeNode (line 12) | TreeNode *sortedArrayToBST(vector<int> &num) {
    method TreeNode (line 15) | TreeNode* dfs(vector<int>& num, int start, int limit) {

FILE: ConvertSortedListtoBinarySearchTree/ConvertSortedListtoBinarySearchTree.cpp
  class Solution (line 18) | class Solution {
    method TreeNode (line 20) | TreeNode *sortedListToBST(ListNode *head) {

FILE: CountandSay/CountandSay.cpp
  class Solution (line 1) | class Solution {
    method string (line 3) | string countAndSay(int n) {

FILE: DecodeWays/DecodeWays.cpp
  class Solution (line 1) | class Solution {
    method numDecodings (line 3) | int numDecodings(string s) {

FILE: DistinctSubsequences/DistinctSubsequences.cpp
  class Solution (line 1) | class Solution {
    method numDistinct (line 3) | int numDistinct(string S, string T) {

FILE: DivideTwoIntegers/DivideTwoIntegers.cpp
  class Solution (line 1) | class Solution {
    method divide (line 3) | int divide(int dividend, int divisor) {

FILE: EditDistance/EditDistance.cpp
  class Solution (line 1) | class Solution {
    method minDistance (line 3) | int minDistance(string word1, string word2) {

FILE: EvaluateReversePolishNotation/EvaluateReversePolishNotation.cpp
  class Solution (line 1) | class Solution {
    method evalRPN (line 3) | int evalRPN(vector<string> &tokens) {

FILE: FirstMissingPositive/FirstMissingPositive.cpp
  class Solution (line 1) | class Solution {
    method firstMissingPositive (line 3) | int firstMissingPositive(int A[], int n) {

FILE: FlattenBinaryTreetoLinkedList/FlattenBinaryTreetoLinkedList.cpp
  class Solution (line 10) | class Solution {
    method flatten (line 12) | void flatten(TreeNode *root) {
    method flatten (line 46) | void flatten(TreeNode *root) {
    method dfs (line 50) | pair<TreeNode*, TreeNode*> dfs(TreeNode* root) {
  class Solution (line 44) | class Solution {
    method flatten (line 12) | void flatten(TreeNode *root) {
    method flatten (line 46) | void flatten(TreeNode *root) {
    method dfs (line 50) | pair<TreeNode*, TreeNode*> dfs(TreeNode* root) {

FILE: GenerateParentheses/GenerateParentheses.cpp
  class Solution (line 1) | class Solution {
    method generateParenthesis (line 3) | vector<string> generateParenthesis(int n) {
    method dfs (line 12) | void dfs(vector<string>& result, string& s, int left, int right) {

FILE: GrayCode/GrayCode.cpp
  class Solution (line 1) | class Solution {
    method grayCode (line 3) | vector<int> grayCode(int n) {
    method grayCode (line 17) | vector<int> grayCode(int n) {
  class Solution (line 15) | class Solution {
    method grayCode (line 3) | vector<int> grayCode(int n) {
    method grayCode (line 17) | vector<int> grayCode(int n) {

FILE: ImplementstrStr/ImplementstrStr.cpp
  class Solution (line 1) | class Solution {

FILE: InsertInterval/InsertInterval.cpp
  class Solution (line 10) | class Solution {
    method insert (line 12) | vector<Interval> insert(vector<Interval> &intervals, Interval newInter...

FILE: IntegertoRoman/IntegertoRoman.cpp
  class Solution (line 1) | class Solution {
    method string (line 3) | string intToRoman(int num) {
    method appendRoman (line 20) | void appendRoman(int n, string& s, char symbol[]) {

FILE: InterleavingString/InterleavingString.cpp
  class Solution (line 1) | class Solution {
    method isInterleave (line 3) | bool isInterleave(string s1, string s2, string s3) {

FILE: JumpGame/JumpGame.cpp
  class Solution (line 1) | class Solution {
    method canJump (line 3) | bool canJump(int A[], int n) {

FILE: JumpGameII/JumpGameII.cpp
  class Solution (line 1) | class Solution {
    method jump (line 3) | int jump(int A[], int n) {

FILE: LRUCache/LRUCache.cc
  class LRUCache (line 1) | class LRUCache{
    method LRUCache (line 3) | LRUCache(int capacity) {
    method get (line 9) | int get(int key) {
    method set (line 22) | void set(int key, int value) {
    type entry (line 50) | struct entry {
    type entry (line 59) | struct entry

FILE: LargestRectangleinHistogram/LargestRectangleinHistogram.cpp
  class Solution (line 1) | class Solution {
    method largestRectangleArea (line 3) | int largestRectangleArea(vector<int>& height) {

FILE: LengthofLastWord/LengthofLastWord.cpp
  class Solution (line 1) | class Solution {
    method lengthOfLastWord (line 3) | int lengthOfLastWord(const char *s) {

FILE: LetterCombinationsofaPhoneNumber/LetterCombinationsofaPhoneNumber.cpp
  class Solution (line 1) | class Solution {
    method letterCombinations (line 3) | vector<string> letterCombinations(string digits) {
    method dfs (line 19) | void dfs(vector<string>& result, string& letter, string& digits, int p...

FILE: LongestCommonPrefix/LongestCommonPrefix.cpp
  class Solution (line 1) | class Solution {
    method string (line 3) | string longestCommonPrefix(vector<string> &strs) {

FILE: LongestConsecutiveSequence/LongestConsecutiveSequence.cpp
  class Solution (line 1) | class Solution {
    method longestConsecutive (line 3) | int longestConsecutive(vector<int> &num) {
    method longestConsecutive (line 34) | int longestConsecutive(vector<int> &num) {
  class Solution (line 32) | class Solution {
    method longestConsecutive (line 3) | int longestConsecutive(vector<int> &num) {
    method longestConsecutive (line 34) | int longestConsecutive(vector<int> &num) {

FILE: LongestPalindromicSubstring/LongestPalindromicSubstring.cpp
  class Solution (line 1) | class Solution {
    method string (line 3) | string longestPalindrome(string s) {

FILE: LongestSubstringWithoutRepeatingCharacters/LongestSubstringWithoutRepeatingCharacters.cpp
  class Solution (line 1) | class Solution {
    method lengthOfLongestSubstring (line 3) | int lengthOfLongestSubstring(string s) {

FILE: LongestValidParentheses/LongestValidParentheses.cpp
  class Solution (line 1) | class Solution {
    method longestValidParentheses (line 3) | int longestValidParentheses(string s) {

FILE: MaxPointsOnALine/MaxPointsOnALine.cpp
  class Solution (line 25) | class Solution {
    method maxPoints (line 27) | int maxPoints(vector<Point> &points) {
    method gcd (line 69) | int gcd(int a, int b) {

FILE: MaximalRectangle/MaximalRectangle.cpp
  class Solution (line 1) | class Solution {
    method maximalRectangle (line 3) | int maximalRectangle(vector<vector<char> > &matrix) {
    method getLargestRectInHistogram (line 28) | int getLargestRectInHistogram(const int height[], int n) {

FILE: MaximumDepthofBinaryTree/MaximumDepthofBinaryTree.cpp
  class Solution (line 10) | class Solution {
    method maxDepth (line 12) | int maxDepth(TreeNode *root) {

FILE: MaximumProductSubarray/MaximumProductSubarray.cpp
  class Solution (line 1) | class Solution {
    method maxProduct (line 3) | int maxProduct(int A[], int n) {

FILE: MaximumSubarray/MaximumSubarray.cpp
  class Solution (line 1) | class Solution {
    method maxSubArray (line 3) | int maxSubArray(int A[], int n) {
    method maxSubArray (line 23) | int maxSubArray(int A[], int n) {
    method maxSubArray (line 30) | int maxSubArray(int A[], int left, int right) {
  class Solution (line 21) | class Solution {
    method maxSubArray (line 3) | int maxSubArray(int A[], int n) {
    method maxSubArray (line 23) | int maxSubArray(int A[], int n) {
    method maxSubArray (line 30) | int maxSubArray(int A[], int left, int right) {

FILE: MedianofTwoSortedArrays/MedianofTwoSortedArrays.cpp
  class Solution (line 1) | class Solution {
    method findMedianSortedArrays (line 3) | double findMedianSortedArrays(int A[], int m, int B[], int n) {
    method findKth (line 12) | int findKth(int k, int A[], int l1, int r1, int B[], int l2, int r2) {

FILE: MergeIntervals/MergeIntervals.cpp
  class Solution (line 18) | class Solution {
    method merge (line 20) | vector<Interval> merge(vector<Interval> &intervals) {

FILE: MergeSortedArray/MergeSortedArray.cpp
  class Solution (line 1) | class Solution {
    method merge (line 3) | void merge(int A[], int m, int B[], int n) {

FILE: MergeTwoSortedLists/MergeTwoSortedLists.cpp
  class Solution (line 9) | class Solution {
    method ListNode (line 11) | ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {

FILE: MergekSortedLists/MergekSortedLists.cpp
  class Solution (line 9) | class Solution {
    method ListNode (line 11) | ListNode *mergeKLists(vector<ListNode *> &lists) {
    method ListNode (line 14) | ListNode* merge(vector<ListNode*>& lists, int left, int right) {

FILE: MinimumDepthofBinaryTree/MinimumDepthofBinaryTree.cpp
  class Solution (line 10) | class Solution {
    method minDepth (line 12) | int minDepth(TreeNode *root) {

FILE: MinimumPathSum/MinimumPathSum.cpp
  class Solution (line 1) | class Solution {
    method minPathSum (line 3) | int minPathSum(vector<vector<int>>& grid) {
    method minPathSum (line 30) | int minPathSum(vector<vector<int> > &grid) {
  class Solution (line 28) | class Solution {
    method minPathSum (line 3) | int minPathSum(vector<vector<int>>& grid) {
    method minPathSum (line 30) | int minPathSum(vector<vector<int> > &grid) {

FILE: MinimumWindowSubstring/MinimumWindowSubstring.cpp
  class Solution (line 1) | class Solution {
    method string (line 3) | string minWindow(string S, string T) {

FILE: MultiplyStrings/MultiplyStrings.cpp
  class Solution (line 1) | class Solution {
    method string (line 3) | string multiply(string num1, string num2) {

FILE: N-Queens/N-Queens.cpp
  class Solution (line 1) | class Solution {
    method solveNQueens (line 3) | vector<vector<string> > solveNQueens(int n) {
    method dfs (line 14) | void dfs(vector<vector<string>>& result, vector<string>& sol,  vector<...

FILE: N-QueensII/N-QueensII.cpp
  class Solution (line 1) | class Solution {
    method totalNQueens (line 3) | int totalNQueens(int n) {
    method dfs (line 9) | void dfs(int& result, int n, int col, int l, int r) {

FILE: NextPermutation/NextPermutation.cpp
  class Solution (line 1) | class Solution {
    method nextPermutation (line 3) | void nextPermutation(vector<int> &num) {

FILE: PalindromeNumber/PalindromeNumber.cpp
  class Solution (line 1) | class Solution {
    method isPalindrome (line 3) | bool isPalindrome(int x) {

FILE: PalindromePartitioning/PalindromePartitioning.cpp
  class Solution (line 1) | class Solution {
    method partition (line 3) | vector<vector<string> > partition(string s) {
    method dfs (line 14) | void dfs(string& s, int p, vector<string>& v) {
    method dynamic (line 31) | void dynamic(string& s) {

FILE: PalindromePartitioningII/PalindromePartitioningII.cpp
  class Solution (line 4) | class Solution {
    method minCut (line 6) | int minCut(string s) {

FILE: PartitionList/PartitionList.cpp
  class Solution (line 9) | class Solution {
    method ListNode (line 11) | ListNode *partition(ListNode *head, int x) {

FILE: Pascal'sTriangle/Pascal'sTriangle.cpp
  class Solution (line 1) | class Solution {
    method generate (line 3) | vector<vector<int> > generate(int numRows) {

FILE: Pascal'sTriangleII/Pascal'sTriangleII.cpp
  class Solution (line 1) | class Solution {
    method getRow (line 3) | vector<int> getRow(int rowIndex) {

FILE: PathSum/PathSum.cpp
  class Solution (line 10) | class Solution {
    method hasPathSum (line 12) | bool hasPathSum(TreeNode *root, int sum) {
    method dfs (line 21) | bool dfs(TreeNode *node, int value, int target) {

FILE: PathSumII/PathSumII.cpp
  class Solution (line 10) | class Solution {
    method pathSum (line 12) | vector<vector<int> > pathSum(TreeNode *root, int sum) {
    method dfs (line 21) | void dfs(TreeNode *node, int value, int sum,

FILE: PermutationSequence/PermutationSequence.cpp
  class Solution (line 4) | class Solution {
    method string (line 6) | string getPermutation(int n, int k) {

FILE: Permutations/Permutations.cpp
  class Solution (line 1) | class Solution {
    method permute (line 3) | vector<vector<int>> permute(vector<int>& num) {
    method dfs (line 12) | void dfs(vector<int>& num, int step, vector<vector<int>>& result) {

FILE: PermutationsII/PermutationsII.cpp
  class Solution (line 1) | class Solution {
    method permuteUnique (line 3) | vector<vector<int> > permuteUnique(vector<int> &num) {
    method getNext (line 12) | bool getNext(vector<int>& num) {
    method helper (line 36) | void helper(vector<vector<int>>& result, vector<int>& num, int x) {
    method permuteUnique (line 55) | vector<vector<int> > permuteUnique(vector<int> &num) {
  class Solution (line 34) | class Solution {
    method permuteUnique (line 3) | vector<vector<int> > permuteUnique(vector<int> &num) {
    method getNext (line 12) | bool getNext(vector<int>& num) {
    method helper (line 36) | void helper(vector<vector<int>>& result, vector<int>& num, int x) {
    method permuteUnique (line 55) | vector<vector<int> > permuteUnique(vector<int> &num) {

FILE: PlusOne/PlusOne.cpp
  class Solution (line 1) | class Solution {
    method plusOne (line 3) | vector<int> plusOne(vector<int>& digits) {

FILE: PopulatingNextRightPointersinEachNode/PopulatingNextRightPointersinEachNode.cpp
  class Solution (line 9) | class Solution {
    method connect (line 11) | void connect(TreeLinkNode *root) {

FILE: PopulatingNextRightPointersinEachNodeII/PopulatingNextRightPointersinEachNodeII.cpp
  class Solution (line 9) | class Solution {
    method connect (line 11) | void connect(TreeLinkNode *root) {

FILE: Pow(x, n)/Pow(x, n).cpp
  class Solution (line 1) | class Solution {
    method pow (line 3) | double pow(double x, int n) {

FILE: RecoverBinarySearchTree/RecoverBinarySearchTree.cpp
  class Solution (line 2) | class Solution {
    method recoverTree (line 4) | void recoverTree(TreeNode *root) {

FILE: RegularExpressionMatching/RegularExpressionMatching.cpp
  class Solution (line 1) | class Solution {
    method isMatch (line 3) | bool isMatch(const char *s, const char *p) {

FILE: RemoveDuplicatesfromSortedArray/RemoveDuplicatesfromSortedArray.cpp
  class Solution (line 1) | class Solution {
    method removeDuplicates (line 3) | int removeDuplicates(int A[], int n) {

FILE: RemoveDuplicatesfromSortedArrayII/RemoveDuplicatesfromSortedArrayII.cpp
  class Solution (line 1) | class Solution {
    method removeDuplicates (line 3) | int removeDuplicates(int A[], int n) {

FILE: RemoveDuplicatesfromSortedList/RemoveDuplicatesfromSortedList.cpp
  class Solution (line 9) | class Solution {
    method ListNode (line 11) | ListNode *deleteDuplicates(ListNode *head) {

FILE: RemoveDuplicatesfromSortedListII/RemoveDuplicatesfromSortedListII.cpp
  class Solution (line 9) | class Solution {
    method ListNode (line 11) | ListNode *deleteDuplicates(ListNode *head) {

FILE: RemoveElement/RemoveElement.cpp
  class Solution (line 1) | class Solution {
    method removeElement (line 3) | int removeElement(int A[], int n, int elem) {

FILE: RemoveNthNodeFromEndofList/RemoveNthNodeFromEndofList.cpp
  class Solution (line 9) | class Solution {
    method ListNode (line 11) | ListNode *removeNthFromEnd(ListNode *head, int n) {

FILE: RestoreIPAddresses/RestoreIPAddresses.cpp
  class Solution (line 1) | class Solution {
    method restoreIpAddresses (line 3) | vector<string> restoreIpAddresses(string s) {
    method dfs (line 10) | void dfs(vector<string>& result, vector<int>& sk, const string& s, int...

FILE: ReverseInteger/ReverseInteger.cpp
  class Solution (line 1) | class Solution {
    method reverse (line 3) | int reverse(int x) {

FILE: ReverseLinkedListII/ReverseLinkedListII.cpp
  class Solution (line 9) | class Solution {
    method ListNode (line 11) | ListNode *reverseBetween(ListNode *head, int m, int n) {

FILE: ReverseNodesink-Group/ReverseNodesink-Group.cpp
  class Solution (line 9) | class Solution {
    method ListNode (line 11) | ListNode *reverseKGroup(ListNode *head, int k) {
    method ListNode (line 50) | ListNode* reverse(ListNode* head) {

FILE: ReverseWordsInAString/ReverseWordsInAString.cpp
  class Solution (line 1) | class Solution {
    method reverseWords (line 3) | void reverseWords(string &s) {
    method reverse (line 40) | void reverse(string& s, int i, int j) {
    method reverseWords (line 52) | void reverseWords(string &s) {
  class Solution (line 50) | class Solution {
    method reverseWords (line 3) | void reverseWords(string &s) {
    method reverse (line 40) | void reverse(string& s, int i, int j) {
    method reverseWords (line 52) | void reverseWords(string &s) {

FILE: RomantoInteger/RomantoInteger.cpp
  class Solution (line 1) | class Solution {
    method romanToInt (line 3) | int romanToInt(string s) {

FILE: RotateImage/RotateImage.cpp
  class Solution (line 1) | class Solution {
    method rotate (line 3) | void rotate(vector<vector<int>>& matrix) {

FILE: RotateList/RotateList.cpp
  class Solution (line 9) | class Solution {
    method ListNode (line 11) | ListNode *rotateRight(ListNode *head, int k) {

FILE: SameTree/SameTree.cpp
  class Solution (line 10) | class Solution {
    method isSameTree (line 12) | bool isSameTree(TreeNode *p, TreeNode *q) {

FILE: ScrambleString/ScrambleString.cpp
  class Solution (line 1) | class Solution {
    method isScramble (line 3) | bool isScramble(string s1, string s2) {
    method isScrambleHelper (line 10) | bool isScrambleHelper(string& s1, int l1, string& s2, int l2, int size) {
    method canScramble (line 25) | bool canScramble(string& s1, int l1, string& s2, int l2, int size) {

FILE: SearchInsertPosition/SearchInsertPosition.cpp
  class Solution (line 1) | class Solution {
    method searchInsert (line 3) | int searchInsert(int A[], int n, int target) {

FILE: Searcha2DMatrix/Searcha2DMatrix.cpp
  class Solution (line 1) | class Solution {
    method searchMatrix (line 3) | bool searchMatrix(vector<vector<int>>& matrix, int target) {
    method isValid (line 24) | bool isValid(vector<int>& row, int target) {

FILE: SearchforaRange/SearchforaRange.cpp
  class Solution (line 1) | class Solution {
    method searchRange (line 3) | vector<int> searchRange(int A[], int n, int target) {
    method find_lower_bound (line 13) | int find_lower_bound(int A[], int n, int target) {
    method find_upper_bound (line 29) | int find_upper_bound(int A[], int n, int target) {

FILE: SearchinRotatedSortedArray/SearchinRotatedSortedArray.cpp
  class Solution (line 1) | class Solution {
    method search (line 3) | int search(int A[], int n, int target) {

FILE: SearchinRotatedSortedArrayII/SearchinRotatedSortedArrayII.cpp
  class Solution (line 1) | class Solution {
    method search (line 3) | bool search(int A[], int n, int target) {

FILE: SetMatrixZeroes/SetMatrixZeroes.cpp
  class Solution (line 1) | class Solution {
    method setZeroes (line 3) | void setZeroes(vector<vector<int>>& matrix) {

FILE: SimplifyPath/SimplifyPath.cpp
  class Solution (line 1) | class Solution {
    method string (line 3) | string simplifyPath(string path) {

FILE: SortColors/SortColors.cpp
  class Solution (line 1) | class Solution {
    method sortColors (line 3) | void sortColors(int A[], int n) {
  class Solution2 (line 25) | class Solution2 {
    method sortColors (line 27) | void sortColors(int A[], int n) {
    method split (line 34) | int split(int A[], int low, int high, int pivot) {

FILE: SortList/SortList.cc
  class Solution (line 9) | class Solution {
    method ListNode (line 11) | ListNode *sortList(ListNode *head) {

FILE: SpiralMatrix/SpiralMatrix.cpp
  class Solution (line 1) | class Solution {
    method spiralOrder (line 3) | vector<int> spiralOrder(vector<vector<int> > &matrix) {

FILE: SpiralMatrixII/SpiralMatrixII.cpp
  class Solution (line 1) | class Solution {
    method generateMatrix (line 3) | vector<vector<int> > generateMatrix(int n) {

FILE: Sqrt(x)/Sqrt(x).cpp
  class Solution (line 1) | class Solution {
    method sqrt (line 3) | int sqrt(int x) {

FILE: StringtoInteger(atoi)/StringtoInteger(atoi).cpp
  class Solution (line 1) | class Solution {
    method atoi (line 3) | int atoi(const char *str) {

FILE: Subsets/Subsets.cpp
  class Solution (line 1) | class Solution {
    method subsets (line 3) | vector<vector<int> > subsets(vector<int>& S) {
    method DFS (line 15) | void DFS(vector<int>& subset, int step, vector<int>& S, vector<vector<...

FILE: SubsetsII/SubsetsII.cpp
  class Solution (line 1) | class Solution {
    method subsetsWithDup (line 3) | vector<vector<int>> subsetsWithDup(vector<int>& S) {
    method DFS (line 19) | void DFS(vector<int>& integers, int start, vector<int>& S, vector<vect...

FILE: SubstringwithConcatenationofAllWords/SubstringwithConcatenationofAllWords.cpp
  class Solution (line 1) | class Solution {
    method findSubstring (line 3) | vector<int> findSubstring(string S, vector<string> &L) {

FILE: SudokuSolver/SudokuSolver.cpp
  class Solution (line 1) | class Solution {
    method solveSudoku (line 7) | void solveSudoku(vector<vector<char>>& board) {
    method isValidSudokuHelper (line 29) | bool isValidSudokuHelper(vector<vector<char>>& board, int step) {

FILE: SumRoottoLeafNumbers/SumRoottoLeafNumbers.cpp
  class Solution (line 10) | class Solution {
    method sumNumbers (line 12) | int sumNumbers(TreeNode *root) {
    method dfs (line 20) | void dfs(TreeNode *node, int val, int& sum) {

FILE: SurroundedRegions/SurroundedRegions.cpp
  class Solution (line 5) | class Solution {
    method solve (line 7) | void solve(vector<vector<char>> &board) {
    method dfs (line 32) | void dfs(int x, int y, vector<vector<char>> &board) {
    method check (line 44) | bool check(int x, int y) {

FILE: SwapNodesinPairs/SwapNodesinPairs.cpp
  class Solution (line 9) | class Solution {
    method ListNode (line 11) | ListNode *swapPairs(ListNode *head) {

FILE: SymmetricTree/SymmetricTree_iteratively.cpp
  class Solution (line 10) | class Solution {
    method isSymmetric (line 12) | bool isSymmetric(TreeNode *root) {

FILE: SymmetricTree/SymmetricTree_recursively.cpp
  class Solution (line 10) | class Solution {
    method isSymmetric (line 12) | bool isSymmetric(TreeNode *root) {
    method dfs (line 20) | bool dfs(TreeNode *lhs, TreeNode *rhs) {

FILE: TextJustification/TextJustification.cpp
  class Solution (line 1) | class Solution {
    method fullJustify (line 3) | vector<string> fullJustify(vector<string>& words, int L) {

FILE: TrappingRainWater/TrappingRainWater.cpp
  class Solution (line 2) | class Solution {
    method trap (line 4) | int trap(int A[], int n) {
    method trap (line 32) | int trap(int A[], int n) {
  class Solution (line 30) | class Solution {
    method trap (line 4) | int trap(int A[], int n) {
    method trap (line 32) | int trap(int A[], int n) {

FILE: Triangle/Triangle.cpp
  class Solution (line 1) | class Solution {
    method minimumTotal (line 3) | int minimumTotal(vector<vector<int> > &triangle) {

FILE: TwoSum/TwoSum.cpp
  function lessthan (line 1) | bool lessthan(const pair<int, int>& lhs, const pair<int, int>& rhs) {
  class Solution (line 7) | class Solution {
    method twoSum (line 9) | vector<int> twoSum(vector<int> &numbers, int target) {

FILE: UniqueBinarySearchTrees/UniqueBinarySearchTrees.cpp
  class Solution (line 1) | class Solution {
    method numTrees (line 3) | int numTrees(int n) {

FILE: UniqueBinarySearchTreesII/UniqueBinarySearchTreesII.cpp
  class Solution (line 10) | class Solution {
    method generateTrees (line 12) | vector<TreeNode *> generateTrees(int n) {
    method generateTreesHelper (line 19) | vector<TreeNode *> generateTreesHelper(int left, int right) {

FILE: UniquePaths/UniquePaths.cpp
  class Solution (line 1) | class Solution {
    method uniquePaths (line 3) | int uniquePaths(int m, int n) {

FILE: UniquePathsII/UniquePathsII.cpp
  class Solution (line 1) | class Solution {
    method uniquePathsWithObstacles (line 3) | int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {

FILE: ValidNumber/ValidNumber.cpp
  class Solution (line 2) | class Solution {
    method accept (line 4) | bool accept(const char* s, int& i, string expected) {
    method acceptRun (line 14) | bool acceptRun(const char* s, int& i, string expected) {
    method isNumber (line 36) | bool isNumber(const char *s) {

FILE: ValidPalindrome/ValidPalindrome.cpp
  class Solution (line 1) | class Solution {
    method isPalindrome (line 3) | bool isPalindrome(string s) {

FILE: ValidParentheses/ValidParentheses.cpp
  class Solution (line 1) | class Solution {
    method isValid (line 3) | bool isValid(string s) {

FILE: ValidSudoku/ValidSudoku.cpp
  class Solution (line 1) | class Solution {
    method isValidSudoku (line 3) | bool isValidSudoku(vector<vector<char>> &board) {

FILE: ValidateBinarySearchTree/ValidateBinarySearchTree.cpp
  class Solution (line 10) | class Solution {
    method isValidBST (line 12) | bool isValidBST(TreeNode *root) {
    method valid (line 20) | bool valid(TreeNode *node, int start, int limit) {
    method isValidBST (line 37) | bool isValidBST(TreeNode *root) {
  class Solution (line 35) | class Solution {
    method isValidBST (line 12) | bool isValidBST(TreeNode *root) {
    method valid (line 20) | bool valid(TreeNode *node, int start, int limit) {
    method isValidBST (line 37) | bool isValidBST(TreeNode *root) {

FILE: WildcardMatching/WildcardMatching.cpp
  class Solution (line 1) | class Solution {
    method isMatch (line 3) | bool isMatch(const char *s, const char *p) {

FILE: WordLadder/WordLadder.cpp
  class Solution (line 1) | class Solution {
    method ladderLength (line 3) | int ladderLength(string start, string end, unordered_set<string> &dict) {

FILE: WordLadderII/WordLadderII.cpp
  class Solution (line 1) | class Solution {
    method buildMap (line 7) | void buildMap(const unordered_set<string>& dict) {
    method buildReverseMap (line 32) | void buildReverseMap(int src, int dst) {
    method dfs (line 55) | void dfs(int u, int v, vector<int>& path, vector<vector<string>>& resu...
    method findLadders (line 71) | vector<vector<string>> findLadders(string start, string end, unordered...

FILE: WordSearch/WordSearch.cpp
  class Solution (line 1) | class Solution {
    method exist (line 3) | bool exist(vector<vector<char>>& board, string word) {
    method isValid (line 33) | bool isValid(int x, int y) {
    method DFS (line 40) | bool DFS(int x, int y, int p) {

FILE: ZigZagConversion/ZigZagConversion.cpp
  class Solution (line 1) | class Solution {
    method string (line 3) | string convert(string s, int nRows) {
Condensed preview — 144 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (159K chars).
[
  {
    "path": ".gitignore",
    "chars": 126,
    "preview": "# Compiled Object files\n*.slo\n*.lo\n*.o\n\n# Compiled Dynamic libraries\n*.so\n*.dylib\n\n# Compiled Static libraries\n*.lai\n*.l"
  },
  {
    "path": "3Sum/3Sum.cpp",
    "chars": 1290,
    "preview": "class Solution {\npublic:\n    vector<vector<int> > threeSum(vector<int> &num) {\n        vector<vector<int>> result;\n     "
  },
  {
    "path": "3SumClosest/3SumClosest.cpp",
    "chars": 809,
    "preview": "class Solution {\npublic:\n    int threeSumClosest(vector<int> &num, int target) {\n        sort(num.begin(), num.end());\n "
  },
  {
    "path": "4Sum/4Sum.cpp",
    "chars": 2296,
    "preview": "\nstruct twoSum {\n    int lf, rt, val;\n    twoSum(int _lf, int _rt, int _val)\n        : lf(_lf), rt(_rt), val(_val) { }\n "
  },
  {
    "path": "AddBinary/AddBinary.cpp",
    "chars": 834,
    "preview": "class Solution {\npublic:\n    string addBinary(string a, string b) {\n        string c;\n        reverse(a.begin(), a.end()"
  },
  {
    "path": "AddTwoNumbers/AddTwoNumbers.cpp",
    "chars": 1494,
    "preview": "/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(in"
  },
  {
    "path": "Anagrams/Anagrams.cpp",
    "chars": 607,
    "preview": "class Solution {\npublic:\n    vector<string> anagrams(vector<string> &strs) {\n        vector<string> result;\n        map<"
  },
  {
    "path": "BalancedBinaryTree/BalancedBinaryTree.cpp",
    "chars": 703,
    "preview": "/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *"
  },
  {
    "path": "BestTimetoBuyandSellStock/BestTimetoBuyandSellStock.cpp",
    "chars": 432,
    "preview": "class Solution {\npublic:\n    int maxProfit(vector<int> &prices) {\n        // Start typing your C/C++ solution below\n    "
  },
  {
    "path": "BestTimetoBuyandSellStockII/BestTimetoBuyandSellStockII.cpp",
    "chars": 1325,
    "preview": "class Solution {\npublic:\n    int maxProfit(vector<int>& prices) {\n        \n        if (prices.empty()) return 0;\n\n      "
  },
  {
    "path": "BestTimetoBuyandSellStockIII/BestTimetoBuyandSellStockIII.cpp",
    "chars": 748,
    "preview": "class Solution {\npublic:\n    int maxProfit(vector<int> &prices) {\n        if (prices.size() < 2) {\n            return 0;"
  },
  {
    "path": "BinaryTreeInorderTraversal/BinaryTreeInorderTraversal.cpp",
    "chars": 1899,
    "preview": "/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *"
  },
  {
    "path": "BinaryTreeLevelOrderTraversal/BinaryTreeLevelOrderTraversal.cpp",
    "chars": 1260,
    "preview": "/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *"
  },
  {
    "path": "BinaryTreeLevelOrderTraversalII/BinaryTreeLevelOrderTraversalII.cpp",
    "chars": 1313,
    "preview": "/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *"
  },
  {
    "path": "BinaryTreeMaximumPathSum/BinaryTreeMaximumPathSum.cpp",
    "chars": 922,
    "preview": "/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *"
  },
  {
    "path": "BinaryTreePostorderTraversal/BinaryTreePostorderTraversal.cc",
    "chars": 1400,
    "preview": "/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *"
  },
  {
    "path": "BinaryTreePreorderTraversal/BinaryTreePreorderTraversal.cpp",
    "chars": 1001,
    "preview": "/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *"
  },
  {
    "path": "BinaryTreeZigzagLevelOrderTraversal/BinaryTreeZigzagLevelOrderTraversal.cpp",
    "chars": 1433,
    "preview": "/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *"
  },
  {
    "path": "ClimbingStairs/ClimbingStairs.cpp",
    "chars": 835,
    "preview": "\n\nclass Matrix {\npublic:\n    int x00, x01;\n    int x10, x11;\n    Matrix() {}\n    Matrix(int _x00, int _x01, int _x10, in"
  },
  {
    "path": "CloneGraph/CloneGraph.cc",
    "chars": 1000,
    "preview": "/**\n * Definition for undirected graph.\n * struct UndirectedGraphNode {\n *     int label;\n *     vector<UndirectedGraphN"
  },
  {
    "path": "CombinationSum/CombinationSum.cpp",
    "chars": 1207,
    "preview": "class Solution {\npublic:\n    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {\n        // Start"
  },
  {
    "path": "CombinationSumII/CombinationSumII.cpp",
    "chars": 1162,
    "preview": "class Solution {\npublic:\n    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {\n        // Start"
  },
  {
    "path": "Combinations/Combinations.cpp",
    "chars": 732,
    "preview": "class Solution {\npublic:\n    vector<vector<int> > combine(int n, int k) {\n        // Start typing your C/C++ solution be"
  },
  {
    "path": "ConstructBinaryTreefromInorderandPostorderTraversal/ConstructBinaryTreefromInorderandPostorderTraversal.cpp",
    "chars": 1079,
    "preview": "/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *"
  },
  {
    "path": "ConstructBinaryTreefromPreorderandInorderTraversal/ConstructBinaryTreefromPreorderandInorderTraversal.cpp",
    "chars": 1082,
    "preview": "/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *"
  },
  {
    "path": "ContainerWithMostWater/ContainerWithMostWater.cpp",
    "chars": 576,
    "preview": "class Solution {\npublic:\n    int maxArea(vector<int>& height) {\n        // Start typing your C/C++ solution below\n      "
  },
  {
    "path": "ConvertSortedArraytoBinarySearchTree/ConvertSortedArraytoBinarySearchTree.cpp",
    "chars": 748,
    "preview": "/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *"
  },
  {
    "path": "ConvertSortedListtoBinarySearchTree/ConvertSortedListtoBinarySearchTree.cpp",
    "chars": 1133,
    "preview": "/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(in"
  },
  {
    "path": "CountandSay/CountandSay.cpp",
    "chars": 734,
    "preview": "class Solution {\npublic:\n    string countAndSay(int n) {\n        // Start typing your C/C++ solution below\n        // DO"
  },
  {
    "path": "DecodeWays/DecodeWays.cpp",
    "chars": 634,
    "preview": "class Solution {\npublic:\n    int numDecodings(string s) {\n        // Start typing your C/C++ solution below\n        // D"
  },
  {
    "path": "DistinctSubsequences/DistinctSubsequences.cpp",
    "chars": 636,
    "preview": "class Solution {\npublic:\n    int numDistinct(string S, string T) {\n        // Start typing your C/C++ solution below\n   "
  },
  {
    "path": "DivideTwoIntegers/DivideTwoIntegers.cpp",
    "chars": 774,
    "preview": "class Solution {\npublic:\n    int divide(int dividend, int divisor) {\n        long long int divid = dividend;\n        lon"
  },
  {
    "path": "EditDistance/EditDistance.cpp",
    "chars": 779,
    "preview": "class Solution {\npublic:\n    int minDistance(string word1, string word2) {\n        vector<vector<int>> dp(word1.size() +"
  },
  {
    "path": "EvaluateReversePolishNotation/EvaluateReversePolishNotation.cpp",
    "chars": 1164,
    "preview": "class Solution {\npublic:\n    int evalRPN(vector<string> &tokens) {\n        stack<int> nums;\n        stack<char> ops;\n   "
  },
  {
    "path": "FirstMissingPositive/FirstMissingPositive.cpp",
    "chars": 438,
    "preview": "class Solution {\npublic:\n    int firstMissingPositive(int A[], int n) {\n        int i = 0;\n        while (i < n) {\n     "
  },
  {
    "path": "FlattenBinaryTreetoLinkedList/FlattenBinaryTreetoLinkedList.cpp",
    "chars": 2012,
    "preview": "/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *"
  },
  {
    "path": "GenerateParentheses/GenerateParentheses.cpp",
    "chars": 753,
    "preview": "class Solution {\npublic:\n    vector<string> generateParenthesis(int n) {\n        vector<string> result;\n        string s"
  },
  {
    "path": "GrayCode/GrayCode.cpp",
    "chars": 713,
    "preview": "class Solution {\npublic:\n    vector<int> grayCode(int n) {\n        // Start typing your C/C++ solution below\n        // "
  },
  {
    "path": "ImplementstrStr/ImplementstrStr.cpp",
    "chars": 854,
    "preview": "class Solution {\npublic:\n    char *strStr(char *haystack, char *needle) {\n        int n = strlen(haystack);\n        int "
  },
  {
    "path": "InsertInterval/InsertInterval.cpp",
    "chars": 1290,
    "preview": "/**\n * Definition for an interval.\n * struct Interval {\n *     int start;\n *     int end;\n *     Interval() : start(0), "
  },
  {
    "path": "IntegertoRoman/IntegertoRoman.cpp",
    "chars": 1030,
    "preview": "class Solution {\npublic:\n    string intToRoman(int num) {\n        // Start typing your C/C++ solution below\n        // D"
  },
  {
    "path": "InterleavingString/InterleavingString.cpp",
    "chars": 1223,
    "preview": "class Solution {\npublic:\n    bool isInterleave(string s1, string s2, string s3) {\n        // Start typing your C/C++ sol"
  },
  {
    "path": "JumpGame/JumpGame.cpp",
    "chars": 533,
    "preview": "class Solution {\npublic:\n    bool canJump(int A[], int n) {\n        // Start typing your C/C++ solution below\n        //"
  },
  {
    "path": "JumpGameII/JumpGameII.cpp",
    "chars": 569,
    "preview": "class Solution {\npublic:\n    int jump(int A[], int n) {\n        // Start typing your C/C++ solution below\n        // DO "
  },
  {
    "path": "LRUCache/LRUCache.cc",
    "chars": 1314,
    "preview": "class LRUCache{\npublic:\n    LRUCache(int capacity) {\n        cap_ = capacity;\n        dummy_.prev = &dummy_;\n        dum"
  },
  {
    "path": "LargestRectangleinHistogram/LargestRectangleinHistogram.cpp",
    "chars": 1114,
    "preview": "class Solution {\npublic:\n    int largestRectangleArea(vector<int>& height) {\n        // Start typing your C/C++ solution"
  },
  {
    "path": "LengthofLastWord/LengthofLastWord.cpp",
    "chars": 417,
    "preview": "class Solution {\npublic:\n    int lengthOfLastWord(const char *s) {\n        int curr = 0;\n        const char* p = s;\n    "
  },
  {
    "path": "LetterCombinationsofaPhoneNumber/LetterCombinationsofaPhoneNumber.cpp",
    "chars": 999,
    "preview": "class Solution {\npublic:\n    vector<string> letterCombinations(string digits) {\n        map<int, string> keypad;\n       "
  },
  {
    "path": "LongestCommonPrefix/LongestCommonPrefix.cpp",
    "chars": 530,
    "preview": "class Solution {\npublic:\n    string longestCommonPrefix(vector<string> &strs) {\n        if (strs.empty()) {\n            "
  },
  {
    "path": "LongestConsecutiveSequence/LongestConsecutiveSequence.cpp",
    "chars": 1450,
    "preview": "class Solution {\npublic:\n    int longestConsecutive(vector<int> &num) {\n        // Start typing your C/C++ solution belo"
  },
  {
    "path": "LongestPalindromicSubstring/LongestPalindromicSubstring.cpp",
    "chars": 787,
    "preview": "class Solution {\npublic:\n    string longestPalindrome(string s) {\n        // Start typing your C/C++ solution below\n    "
  },
  {
    "path": "LongestSubstringWithoutRepeatingCharacters/LongestSubstringWithoutRepeatingCharacters.cpp",
    "chars": 514,
    "preview": "class Solution {\npublic:\n    int lengthOfLongestSubstring(string s) {\n        int hash[256];\n        for (int i = 0; i <"
  },
  {
    "path": "LongestValidParentheses/LongestValidParentheses.cpp",
    "chars": 1271,
    "preview": "class Solution {\npublic:\n    int longestValidParentheses(string s) {\n        // Start typing your C/C++ solution below\n "
  },
  {
    "path": "MaxPointsOnALine/MaxPointsOnALine.cpp",
    "chars": 1914,
    "preview": "/**\n * Definition for a point.\n * struct Point {\n *     int x;\n *     int y;\n *     Point() : x(0), y(0) {}\n *     Point"
  },
  {
    "path": "MaximalRectangle/MaximalRectangle.cpp",
    "chars": 1754,
    "preview": "class Solution {\npublic:\n    int maximalRectangle(vector<vector<char> > &matrix) {\n        // Start typing your C/C++ so"
  },
  {
    "path": "MaximumDepthofBinaryTree/MaximumDepthofBinaryTree.cpp",
    "chars": 513,
    "preview": "/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *"
  },
  {
    "path": "MaximumProductSubarray/MaximumProductSubarray.cpp",
    "chars": 524,
    "preview": "class Solution {\npublic:\n    int maxProduct(int A[], int n) {\n        if (n == 0) {\n            return 0;\n        }\n    "
  },
  {
    "path": "MaximumSubarray/MaximumSubarray.cpp",
    "chars": 1330,
    "preview": "class Solution {\npublic:\n    int maxSubArray(int A[], int n) {\n        // Start typing your C/C++ solution below\n       "
  },
  {
    "path": "MedianofTwoSortedArrays/MedianofTwoSortedArrays.cpp",
    "chars": 1180,
    "preview": "class Solution {\npublic:\n    double findMedianSortedArrays(int A[], int m, int B[], int n) {\n        if ((m + n) & 1) {\n"
  },
  {
    "path": "MergeIntervals/MergeIntervals.cpp",
    "chars": 964,
    "preview": "/**\n * Definition for an interval.\n * struct Interval {\n *     int start;\n *     int end;\n *     Interval() : start(0), "
  },
  {
    "path": "MergeSortedArray/MergeSortedArray.cpp",
    "chars": 517,
    "preview": "class Solution {\npublic:\n    void merge(int A[], int m, int B[], int n) {\n        // Start typing your C/C++ solution be"
  },
  {
    "path": "MergeTwoSortedLists/MergeTwoSortedLists.cpp",
    "chars": 1116,
    "preview": "/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(in"
  },
  {
    "path": "MergekSortedLists/MergekSortedLists.cpp",
    "chars": 1243,
    "preview": "/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(in"
  },
  {
    "path": "MinimumDepthofBinaryTree/MinimumDepthofBinaryTree.cpp",
    "chars": 679,
    "preview": "/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *"
  },
  {
    "path": "MinimumPathSum/MinimumPathSum.cpp",
    "chars": 1482,
    "preview": "class Solution {\npublic:\n    int minPathSum(vector<vector<int>>& grid) {\n        // Start typing your C/C++ solution bel"
  },
  {
    "path": "MinimumWindowSubstring/MinimumWindowSubstring.cpp",
    "chars": 1117,
    "preview": "class Solution {\npublic:\n    string minWindow(string S, string T) {\n        string result(\"\");\n        map<char, int> ne"
  },
  {
    "path": "MultiplyStrings/MultiplyStrings.cpp",
    "chars": 1249,
    "preview": "class Solution {\npublic:\n    string multiply(string num1, string num2) {\n        // Start typing your C/C++ solution bel"
  },
  {
    "path": "N-Queens/N-Queens.cpp",
    "chars": 1130,
    "preview": "class Solution {\npublic:\n    vector<vector<string> > solveNQueens(int n) {\n        vector<vector<string>> result;\n      "
  },
  {
    "path": "N-QueensII/N-QueensII.cpp",
    "chars": 552,
    "preview": "class Solution {\npublic:\n    int totalNQueens(int n) {\n        int result = 0;\n        dfs(result, n, 0, 0, 0);\n        "
  },
  {
    "path": "NextPermutation/NextPermutation.cpp",
    "chars": 503,
    "preview": "class Solution {\npublic:\n    void nextPermutation(vector<int> &num) {\n        int i = num.size() - 1;\n        while (i >"
  },
  {
    "path": "PalindromeNumber/PalindromeNumber.cpp",
    "chars": 474,
    "preview": "class Solution {\npublic:\n    bool isPalindrome(int x) {\n        // Start typing your C/C++ solution below\n        // DO "
  },
  {
    "path": "PalindromePartitioning/PalindromePartitioning.cpp",
    "chars": 1182,
    "preview": "class Solution {\npublic:\n    vector<vector<string> > partition(string s) {\n        // Start typing your C/C++ solution b"
  },
  {
    "path": "PalindromePartitioningII/PalindromePartitioningII.cpp",
    "chars": 711,
    "preview": "const int MAXN = 2010;\nconst int INFS = 0x3fffffff;\n\nclass Solution {\npublic:\n\tint minCut(string s) {\n\t\t// Start typing "
  },
  {
    "path": "PartitionList/PartitionList.cpp",
    "chars": 1050,
    "preview": "/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(in"
  },
  {
    "path": "Pascal'sTriangle/Pascal'sTriangle.cpp",
    "chars": 580,
    "preview": "class Solution {\npublic:\n    vector<vector<int> > generate(int numRows) {\n        vector<vector<int>> triangle;\n        "
  },
  {
    "path": "Pascal'sTriangleII/Pascal'sTriangleII.cpp",
    "chars": 618,
    "preview": "class Solution {\npublic:\n    vector<int> getRow(int rowIndex) {\n        // Start typing your C/C++ solution below\n      "
  },
  {
    "path": "PathSum/PathSum.cpp",
    "chars": 946,
    "preview": "/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *"
  },
  {
    "path": "PathSumII/PathSumII.cpp",
    "chars": 1126,
    "preview": "/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *"
  },
  {
    "path": "PermutationSequence/PermutationSequence.cpp",
    "chars": 906,
    "preview": "\nconst int factorial[10] = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880};\n\nclass Solution {\npublic:\n    string getPerm"
  },
  {
    "path": "Permutations/Permutations.cpp",
    "chars": 638,
    "preview": "class Solution {\npublic:\n    vector<vector<int>> permute(vector<int>& num) {\n        // Start typing your C/C++ solution"
  },
  {
    "path": "PermutationsII/PermutationsII.cpp",
    "chars": 1536,
    "preview": "class Solution {\npublic:\n    vector<vector<int> > permuteUnique(vector<int> &num) {\n        vector<vector<int>> result;\n"
  },
  {
    "path": "PlusOne/PlusOne.cpp",
    "chars": 590,
    "preview": "class Solution {\npublic:\n    vector<int> plusOne(vector<int>& digits) {\n        // Start typing your C/C++ solution belo"
  },
  {
    "path": "PopulatingNextRightPointersinEachNode/PopulatingNextRightPointersinEachNode.cpp",
    "chars": 687,
    "preview": "/**\n * Definition for binary tree with next pointer.\n * struct TreeLinkNode {\n *  int val;\n *  TreeLinkNode *left, *righ"
  },
  {
    "path": "PopulatingNextRightPointersinEachNodeII/PopulatingNextRightPointersinEachNodeII.cpp",
    "chars": 1394,
    "preview": "/**\n * Definition for binary tree with next pointer.\n * struct TreeLinkNode {\n *  int val;\n *  TreeLinkNode *left, *righ"
  },
  {
    "path": "Pow(x, n)/Pow(x, n).cpp",
    "chars": 430,
    "preview": "class Solution {\npublic:\n    double pow(double x, int n) {\n        // Start typing your C/C++ solution below\n        // "
  },
  {
    "path": "README.md",
    "chars": 530,
    "preview": "leetcode     [![Total views](https://sourcegraph.com/api/repos/github.com/kedebug/leetcode/counters/views.png)](https://"
  },
  {
    "path": "RecoverBinarySearchTree/RecoverBinarySearchTree.cpp",
    "chars": 1306,
    "preview": "// O(n) time, O(1) space\nclass Solution {\npublic:\n    void recoverTree(TreeNode *root) {\n        TreeNode* node = root;\n"
  },
  {
    "path": "RegularExpressionMatching/RegularExpressionMatching.cpp",
    "chars": 781,
    "preview": "class Solution {\npublic:\n    bool isMatch(const char *s, const char *p) {\n        // Start typing your C/C++ solution be"
  },
  {
    "path": "RemoveDuplicatesfromSortedArray/RemoveDuplicatesfromSortedArray.cpp",
    "chars": 383,
    "preview": "class Solution {\npublic:\n    int removeDuplicates(int A[], int n) {\n        // Start typing your C/C++ solution below\n  "
  },
  {
    "path": "RemoveDuplicatesfromSortedArrayII/RemoveDuplicatesfromSortedArrayII.cpp",
    "chars": 615,
    "preview": "class Solution {\npublic:\n    int removeDuplicates(int A[], int n) {\n        // Start typing your C/C++ solution below\n  "
  },
  {
    "path": "RemoveDuplicatesfromSortedList/RemoveDuplicatesfromSortedList.cpp",
    "chars": 611,
    "preview": "/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(in"
  },
  {
    "path": "RemoveDuplicatesfromSortedListII/RemoveDuplicatesfromSortedListII.cpp",
    "chars": 819,
    "preview": "/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(in"
  },
  {
    "path": "RemoveElement/RemoveElement.cpp",
    "chars": 400,
    "preview": "class Solution {\npublic:\n    int removeElement(int A[], int n, int elem) {\n        // Start typing your C/C++ solution b"
  },
  {
    "path": "RemoveNthNodeFromEndofList/RemoveNthNodeFromEndofList.cpp",
    "chars": 834,
    "preview": "/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(in"
  },
  {
    "path": "RestoreIPAddresses/RestoreIPAddresses.cpp",
    "chars": 999,
    "preview": "class Solution {\npublic:\n    vector<string> restoreIpAddresses(string s) {\n        vector<string> result;\n        vector"
  },
  {
    "path": "ReverseInteger/ReverseInteger.cpp",
    "chars": 426,
    "preview": "class Solution {\npublic:\n    int reverse(int x) {\n        // Start typing your C/C++ solution below\n        // DO NOT wr"
  },
  {
    "path": "ReverseLinkedListII/ReverseLinkedListII.cpp",
    "chars": 915,
    "preview": "/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(in"
  },
  {
    "path": "ReverseNodesink-Group/ReverseNodesink-Group.cpp",
    "chars": 1462,
    "preview": "/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(in"
  },
  {
    "path": "ReverseWordsInAString/ReverseWordsInAString.cpp",
    "chars": 1602,
    "preview": "class Solution {\npublic:\n    void reverseWords(string &s) {\n        int i = 0;\n        int j = s.size() - 1;\n\n        wh"
  },
  {
    "path": "RomantoInteger/RomantoInteger.cpp",
    "chars": 652,
    "preview": "class Solution {\npublic:\n    int romanToInt(string s) {\n\t\t// Start typing your C/C++ solution below\n\t\t// DO NOT write in"
  },
  {
    "path": "RotateImage/RotateImage.cpp",
    "chars": 569,
    "preview": "class Solution {\npublic:\n    void rotate(vector<vector<int>>& matrix) {\n        // Start typing your C/C++ solution belo"
  },
  {
    "path": "RotateList/RotateList.cpp",
    "chars": 1054,
    "preview": "/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(in"
  },
  {
    "path": "SameTree/SameTree.cpp",
    "chars": 692,
    "preview": "/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *"
  },
  {
    "path": "ScrambleString/ScrambleString.cpp",
    "chars": 1178,
    "preview": "class Solution {\npublic:\n    bool isScramble(string s1, string s2) {\n        // Start typing your C/C++ solution below\n "
  },
  {
    "path": "SearchInsertPosition/SearchInsertPosition.cpp",
    "chars": 506,
    "preview": "class Solution {\npublic:\n    int searchInsert(int A[], int n, int target) {\n        // Start typing your C/C++ solution "
  },
  {
    "path": "Searcha2DMatrix/Searcha2DMatrix.cpp",
    "chars": 1109,
    "preview": "class Solution {\npublic:\n    bool searchMatrix(vector<vector<int>>& matrix, int target) {\n        // Start typing your C"
  },
  {
    "path": "SearchforaRange/SearchforaRange.cpp",
    "chars": 1193,
    "preview": "class Solution {\npublic:\n    vector<int> searchRange(int A[], int n, int target) {\n        // Start typing your C/C++ so"
  },
  {
    "path": "SearchinRotatedSortedArray/SearchinRotatedSortedArray.cpp",
    "chars": 738,
    "preview": "class Solution {\npublic:\n    int search(int A[], int n, int target) {\n        // Start typing your C/C++ solution below\n"
  },
  {
    "path": "SearchinRotatedSortedArrayII/SearchinRotatedSortedArrayII.cpp",
    "chars": 982,
    "preview": "class Solution {\npublic:\n    bool search(int A[], int n, int target) {\n        // Start typing your C/C++ solution below"
  },
  {
    "path": "SetMatrixZeroes/SetMatrixZeroes.cpp",
    "chars": 1379,
    "preview": "class Solution {\npublic:\n    void setZeroes(vector<vector<int>>& matrix) {\n        // Start typing your C/C++ solution b"
  },
  {
    "path": "SimplifyPath/SimplifyPath.cpp",
    "chars": 1002,
    "preview": "class Solution {\npublic:\n    string simplifyPath(string path) {\n        // Start typing your C/C++ solution below\n      "
  },
  {
    "path": "SortColors/SortColors.cpp",
    "chars": 1012,
    "preview": "class Solution {\npublic:\n    void sortColors(int A[], int n) {\n        int p0 = -1;\n        int p1 = 0;\n        int p2 ="
  },
  {
    "path": "SortList/SortList.cc",
    "chars": 1784,
    "preview": "/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(in"
  },
  {
    "path": "SpiralMatrix/SpiralMatrix.cpp",
    "chars": 1151,
    "preview": "class Solution {\npublic:\n\tvector<int> spiralOrder(vector<vector<int> > &matrix) {\n        vector<int> result;\n        if"
  },
  {
    "path": "SpiralMatrixII/SpiralMatrixII.cpp",
    "chars": 1061,
    "preview": "class Solution {\npublic:\n    vector<vector<int> > generateMatrix(int n) {\n        vector<vector<int>> matrix(n, vector<i"
  },
  {
    "path": "Sqrt(x)/Sqrt(x).cpp",
    "chars": 514,
    "preview": "class Solution {\npublic:\n    int sqrt(int x) {\n        // Start typing your C/C++ solution below\n        // DO NOT write"
  },
  {
    "path": "StringtoInteger(atoi)/StringtoInteger(atoi).cpp",
    "chars": 879,
    "preview": "class Solution {\npublic:\n    int atoi(const char *str) {\n        // Start typing your C/C++ solution below\n        // DO"
  },
  {
    "path": "Subsets/Subsets.cpp",
    "chars": 715,
    "preview": "class Solution {\npublic:\n    vector<vector<int> > subsets(vector<int>& S) {\n        // Start typing your C/C++ solution "
  },
  {
    "path": "SubsetsII/SubsetsII.cpp",
    "chars": 1032,
    "preview": "class Solution {\npublic:\n    vector<vector<int>> subsetsWithDup(vector<int>& S) {\n        // Start typing your C/C++ sol"
  },
  {
    "path": "SubstringwithConcatenationofAllWords/SubstringwithConcatenationofAllWords.cpp",
    "chars": 1041,
    "preview": "class Solution {\npublic:\n    vector<int> findSubstring(string S, vector<string> &L) {\n        vector<int> result;\n      "
  },
  {
    "path": "SudokuSolver/SudokuSolver.cpp",
    "chars": 1839,
    "preview": "class Solution {\npublic:\n    bool visited_cells[20][20];\n    bool visited_row[20][20];\n    bool visited_col[20][20];\n   "
  },
  {
    "path": "SumRoottoLeafNumbers/SumRoottoLeafNumbers.cpp",
    "chars": 851,
    "preview": "/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *"
  },
  {
    "path": "SurroundedRegions/SurroundedRegions.cpp",
    "chars": 1129,
    "preview": "\nconst int dx[4] = {0, 0, 1, -1};\nconst int dy[4] = {1, -1, 0, 0};\n\nclass Solution {\npublic:\n\tvoid solve(vector<vector<c"
  },
  {
    "path": "SwapNodesinPairs/SwapNodesinPairs.cpp",
    "chars": 875,
    "preview": "/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(in"
  },
  {
    "path": "SymmetricTree/SymmetricTree_iteratively.cpp",
    "chars": 1016,
    "preview": "/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *"
  },
  {
    "path": "SymmetricTree/SymmetricTree_recursively.cpp",
    "chars": 858,
    "preview": "/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *"
  },
  {
    "path": "TextJustification/TextJustification.cpp",
    "chars": 2181,
    "preview": "class Solution {\npublic:\n    vector<string> fullJustify(vector<string>& words, int L) {\n        // Start typing your C/C"
  },
  {
    "path": "TrappingRainWater/TrappingRainWater.cpp",
    "chars": 1506,
    "preview": "// O(n) time, O(n) space\nclass Solution {\npublic:\n    int trap(int A[], int n) {\n        // Start typing your C/C++ solu"
  },
  {
    "path": "Triangle/Triangle.cpp",
    "chars": 362,
    "preview": "class Solution {\npublic:\n    int minimumTotal(vector<vector<int> > &triangle) {\n        int level = triangle.size();\n   "
  },
  {
    "path": "TwoSum/TwoSum.cpp",
    "chars": 1064,
    "preview": "bool lessthan(const pair<int, int>& lhs, const pair<int, int>& rhs) {\n    if (lhs.first == rhs.first) \n        return lh"
  },
  {
    "path": "UniqueBinarySearchTrees/UniqueBinarySearchTrees.cpp",
    "chars": 378,
    "preview": "class Solution {\npublic:\n    int numTrees(int n) {\n        // Start typing your C/C++ solution below\n        // DO NOT w"
  },
  {
    "path": "UniqueBinarySearchTreesII/UniqueBinarySearchTreesII.cpp",
    "chars": 1206,
    "preview": "/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *"
  },
  {
    "path": "UniquePaths/UniquePaths.cpp",
    "chars": 520,
    "preview": "class Solution {\npublic:\n    int uniquePaths(int m, int n) {\n        // Start typing your C/C++ solution below\n        /"
  },
  {
    "path": "UniquePathsII/UniquePathsII.cpp",
    "chars": 948,
    "preview": "class Solution {\npublic:\n    int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {\n        // Start typing y"
  },
  {
    "path": "ValidNumber/ValidNumber.cpp",
    "chars": 1701,
    "preview": "// NFA\nclass Solution {\npublic:\n    bool accept(const char* s, int& i, string expected) {\n        for (int j = 0; j < ex"
  },
  {
    "path": "ValidPalindrome/ValidPalindrome.cpp",
    "chars": 871,
    "preview": "class Solution {\npublic:\n    bool isPalindrome(string s) {\n        // Start typing your C/C++ solution below\n        // "
  },
  {
    "path": "ValidParentheses/ValidParentheses.cpp",
    "chars": 726,
    "preview": "class Solution {\npublic:\n    bool isValid(string s) {\n        // Start typing your C/C++ solution below\n        // DO NO"
  },
  {
    "path": "ValidSudoku/ValidSudoku.cpp",
    "chars": 781,
    "preview": "class Solution {\npublic:\n    bool isValidSudoku(vector<vector<char>> &board) {\n        vector<vector<bool>> rows(9, vect"
  },
  {
    "path": "ValidateBinarySearchTree/ValidateBinarySearchTree.cpp",
    "chars": 2181,
    "preview": "/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *"
  },
  {
    "path": "WildcardMatching/WildcardMatching.cpp",
    "chars": 1446,
    "preview": "class Solution {\npublic:\n    bool isMatch(const char *s, const char *p) {\n        // Start typing your C/C++ solution be"
  },
  {
    "path": "WordLadder/WordLadder.cpp",
    "chars": 1094,
    "preview": "class Solution {\npublic:\n    int ladderLength(string start, string end, unordered_set<string> &dict) {\n        queue<str"
  },
  {
    "path": "WordLadderII/WordLadderII.cpp",
    "chars": 2775,
    "preview": "class Solution {\nprivate:\n    vector<string> vdict;\n    vector<vector<int>> map;\n    vector<vector<int>> prev;\n\n    void"
  },
  {
    "path": "WordSearch/WordSearch.cpp",
    "chars": 1845,
    "preview": "class Solution {\npublic:\n    bool exist(vector<vector<char>>& board, string word) {\n        // Start typing your C/C++ s"
  },
  {
    "path": "ZigZagConversion/ZigZagConversion.cpp",
    "chars": 645,
    "preview": "class Solution {\npublic:\n    string convert(string s, int nRows) {\n        // Start typing your C/C++ solution below\n   "
  }
]

About this extraction

This page contains the full source code of the kedebug/leetcode GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 144 files (140.0 KB), approximately 42.1k tokens, and a symbol index with 372 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!