[
  {
    "path": ".gitattributes",
    "content": "# Auto detect text files and perform LF normalization\n* text=auto\n\n# Custom for Visual Studio\n*.cs     diff=csharp\n*.sln    merge=union\n*.csproj merge=union\n*.vbproj merge=union\n*.fsproj merge=union\n*.dbproj merge=union\n\n# Standard to msysgit\n*.doc\t diff=astextplain\n*.DOC\t diff=astextplain\n*.docx diff=astextplain\n*.DOCX diff=astextplain\n*.dot  diff=astextplain\n*.DOT  diff=astextplain\n*.pdf  diff=astextplain\n*.PDF\t diff=astextplain\n*.rtf\t diff=astextplain\n*.RTF\t diff=astextplain\n"
  },
  {
    "path": ".gitignore",
    "content": "#################\n## Eclipse\n#################\n\n*.pydevproject\n.project\n.metadata\nbin/\ntmp/\n*.tmp\n*.bak\n*.swp\n*~.nib\nlocal.properties\n.classpath\n.settings/\n.loadpath\n\n# External tool builders\n.externalToolBuilders/\n\n# Locally stored \"Eclipse launch configurations\"\n*.launch\n\n# CDT-specific\n.cproject\n\n# PDT-specific\n.buildpath\n\n\n#################\n## Visual Studio\n#################\n\n## Ignore Visual Studio temporary files, build results, and\n## files generated by popular Visual Studio add-ons.\n\n# User-specific files\n*.suo\n*.user\n*.sln.docstates\n\n# Build results\n[Dd]ebug/\n[Rr]elease/\n*_i.c\n*_p.c\n*.ilk\n*.meta\n*.obj\n*.pch\n*.pdb\n*.pgc\n*.pgd\n*.rsp\n*.sbr\n*.tlb\n*.tli\n*.tlh\n*.tmp\n*.vspscc\n.builds\n*.dotCover\n\n## TODO: If you have NuGet Package Restore enabled, uncomment this\n#packages/\n\n# Visual C++ cache files\nipch/\n*.aps\n*.ncb\n*.opensdf\n*.sdf\n\n# Visual Studio profiler\n*.psess\n*.vsp\n\n# ReSharper is a .NET coding add-in\n_ReSharper*\n\n# Installshield output folder\n[Ee]xpress\n\n# DocProject is a documentation generator add-in\nDocProject/buildhelp/\nDocProject/Help/*.HxT\nDocProject/Help/*.HxC\nDocProject/Help/*.hhc\nDocProject/Help/*.hhk\nDocProject/Help/*.hhp\nDocProject/Help/Html2\nDocProject/Help/html\n\n# Click-Once directory\npublish\n\n# Others\n[Bb]in\n[Oo]bj\nsql\nTestResults\n*.Cache\nClientBin\nstylecop.*\n~$*\n*.dbmdl\nGenerated_Code #added for RIA/Silverlight projects\n\n# Backup & report files from converting an old project file to a newer\n# Visual Studio version. Backup files are not needed, because we have git ;-)\n_UpgradeReport_Files/\nBackup*/\nUpgradeLog*.XML\n\n\n\n############\n## Windows\n############\n\n# Windows image file caches\nThumbs.db\n\n# Folder config file\nDesktop.ini\n\n\n#############\n## Python\n#############\n\n*.py[co]\n\n# Packages\n*.egg\n*.egg-info\ndist\nbuild\neggs\nparts\nbin\nvar\nsdist\ndevelop-eggs\n.installed.cfg\n\n# Installer logs\npip-log.txt\n\n# Unit test / coverage reports\n.coverage\n.tox\n\n#Translations\n*.mo\n\n#Mr Developer\n.mr.developer.cfg\n\n# Mac crap\n.DS_Store\n"
  },
  {
    "path": "3Sum.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 19, 2013\n Update:     Sep 22, 2013\n Problem:    3Sum\n Difficulty: Medium\n Source:     http://leetcode.com/onlinejudge#question_15\n Notes:\n Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? \n Find all unique triplets in the array which gives the sum of zero.\n Note:\n Elements in a triplet (a,b,c) must be in non-descending order. (ie, a <= b <= c)\n The solution set must not contain duplicate triplets.\n For example, given array S = {-1 0 1 2 -1 -4},\n A solution set is:\n (-1, 0, 1)\n (-1, -1, 2)\n\n Solution: Simplify '3sum' to '2sum' O(n^2). http://en.wikipedia.org/wiki/3SUM\n*/\n\nclass Solution {\npublic:\n    vector<vector<int> > threeSum(vector<int> &num) {\n        vector<vector<int>> res;\n        sort(num.begin(), num.end());\n        int N = num.size();\n        for (int i = 0; i < N-2 && num[i] <= 0; ++i)\n        {\n            if (i > 0 && num[i] == num[i-1])\n                continue; // avoid duplicates\n            int twosum = 0 - num[i];\n            int l = i + 1, r = N - 1;\n            while (l < r)\n            {\n                int sum = num[l] + num[r];\n                if (sum < twosum)\n                    l++;\n                else if (sum > twosum)\n                    r--;\n                else {\n                    res.push_back(vector<int>{num[i],num[l],num[r]});\n                    l++; r--;\n                    while (l < r && num[l] == num[l-1]) l++;  // avoid duplicates\n                    while (l < r && num[r] == num[r+1]) r--;  // avoid duplicates\n                }\n            }\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "3SumClosest.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 20, 2013\n Problem:    3Sum Closest\n Difficulty: Medium\n Source:     http://leetcode.com/onlinejudge#question_16\n Notes:\n Given an array S of n integers, find three integers in S such that the sum is closest to \n a given number, target. Return the sum of the three integers. \n You may assume that each input would have exactly one solution.\n For example, given array S = {-1 2 1 -4}, and target = 1.\n The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).\n\n Solution: Similar to 3Sum, taking O(n^2) time complexity.\n */\n\nclass Solution {\npublic:\n    int threeSumClosest(vector<int> &num, int target) {\n        int N = num.size();\n        if (N < 3) return 0;\n        int res = num[0] + num[1] + num[2];\n        sort(num.begin(), num.end());\n        for (int i = 0; i < N-2; ++i)\n        {\n            int l = i + 1, r = N - 1;\n            while (l < r)\n            {\n                int threesum = num[i] + num[l] + num[r];\n                if (threesum == target) return target;\n                else if (threesum < target) ++l;\n                else --r;\n                if (abs(threesum - target) < abs(res - target))\n                    res = threesum;\n            }\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "4Sum.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 20, 2013\n Update:     Sep 26, 2013\n Problem:    4Sum\n Difficulty: Medium\n Source:     http://leetcode.com/onlinejudge#question_18\n Notes:\n Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? \n Find all unique triplets in the array which gives the sum of zero.\n Note:\n Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? \n Find all unique quadruplets in the array which gives the sum of target.\n Note:\n Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a <= b <= c <= d)\n The solution set must not contain duplicate quadruplets.\n For example, given array S = {1 0 -1 0 -2 2}, and target = 0.\n A solution set is:\n (-1,  0, 0, 1)\n (-2, -1, 1, 2)\n (-2,  0, 0, 2)\n\n Solution: Similar to 3Sum, 2Sum.\n */\n\nclass Solution {\npublic:\n    vector<vector<int> > fourSum(vector<int> &num, int target) {\n        int N = num.size();\n        vector<vector<int> > res;\n        if (N < 4) return res;\n        sort(num.begin(), num.end());\n        for (int i = 0; i < N; ++i)\n        {\n            if (i > 0 && num[i] == num[i-1]) continue; // avoid duplicates\n            for (int j = i+1; j < N; ++j)\n            {\n                if (j > i+1 && num[j] == num[j-1]) continue; // avoid duplicates\n                int twosum = target - num[i] - num[j];\n                int l = j + 1, r = N - 1;\n                while (l < r)\n                {\n                    int sum = num[l] + num[r];\n                    if (sum == twosum) {\n                        vector<int> quadruplet(4);\n                        quadruplet[0] = num[i];\n                        quadruplet[1] = num[j];\n                        quadruplet[2] = num[l];\n                        quadruplet[3] = num[r];\n                        res.push_back(quadruplet);\n                        while (l < r && num[l+1] == num[l]) l++; // avoid duplicates\n                        while (l < r && num[r-1] == num[r]) r--; // avoid duplicates\n                        l++; r--;\n                    }\n                    else if (sum < twosum) l++;\n                    else r--;\n                }\n            }\n        }\n        return res;\n    }\n};"
  },
  {
    "path": "AddBinary.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 17, 2013\n Update:     Sep 25, 2013\n Problem:    Add Binary\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_67\n Notes:\n Given two binary strings, return their sum (also a binary string).\n For example,\n a = \"11\"\n b = \"1\"\n Return \"100\".\n\n Solution: '1'-'0' = 1.\n */\n\nclass Solution {\npublic:\n    string addBinary(string a, string b) {\n        int N = a.size(), M = b.size(), K = max(N, M);\n        string res(K, ' ');\n        int carry = 0;\n        int i = N-1, j = M-1, k = K-1;\n        while (i >= 0 || j >= 0)\n        {\n            int sum = carry;\n            if (i >= 0) sum += a[i--] - '0';\n            if (j >= 0) sum += b[j--] - '0';\n            carry = sum / 2;\n            res[k--] = sum % 2 + '0';\n        }\n        if (carry == 1)\n            res.insert(res.begin(), '1');\n        return res;\n    }\n};"
  },
  {
    "path": "AddTwoNumbers.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Jan 16, 2013\n Update:     Sep 22, 2013\n Problem:    Add Two Numbers\n Difficulty: easy\n Source:     http://www.leetcode.com/onlinejudge\n Notes:\n You are given two linked lists representing two non-negative numbers. \n The digits are stored in reverse order and each of their nodes contain a single digit. \n Add the two numbers and return it as a linked list.\n\n Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)\n Output: 7 -> 0 -> 8\n\n Solution: dummy head...\n\n */\n\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(int x) : val(x), next(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {\n        ListNode dummy(0), *cur = &dummy;\n        int carry = 0;\n        while (l1 || l2 || carry)\n        {\n            int sum = carry;\n            if (l1) {\n                sum += l1->val;\n                l1 = l1->next;\n            }\n            if (l2) {\n                sum += l2->val;\n                l2 = l2->next;\n            }\n            carry = sum >= 10 ? 1 : 0;\n            sum %= 10;\n            ListNode *newNode = new ListNode(sum);\n            cur->next = newNode;\n            cur = newNode;\n        }\n        return dummy.next;\n    }\n};\n"
  },
  {
    "path": "Anagrams.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 17, 2013\n Update:     Sep 25, 2013\n Problem:    Anagrams\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_49\n Notes:\n Given an array of strings, return all groups of strings that are anagrams.\n Note: All inputs will be in lower-case.\n\n Solution: Sort the string to see if they're anagrams.\n           Solution 1 is simpler than 2.\n */\n\nclass Solution {\npublic:\n    vector<string> anagrams(vector<string> &strs) {\n        return anagrams_1(strs);\n    }\n    \n    // solution 1\n    vector<string> anagrams_1(vector<string> &strs) {\n        typedef map<string, vector<int> > MAP;\n        MAP map;\n        for (int i = 0; i < strs.size(); ++i) \n        {\n            string s = strs[i];\n            sort(s.begin(), s.end());\n            map[s].push_back(i);\n        }\n        vector<string> res;\n        MAP::iterator it = map.begin();\n        for (; it != map.end(); it++) \n        {\n            vector<int> &anagrams = it->second;\n            if (anagrams.size() > 1) {\n                for (int i = 0; i < anagrams.size(); ++i)\n                    res.push_back(strs[anagrams[i]]);\n            }\n        }\n        return res;\n    }\n    \n    // solution 2\n    vector<string> anagrams_2(vector<string> &strs) {\n        typedef unordered_map<string, int > MAP;\n        vector<string> res;\n        MAP anagram;\n        for (int i = 0; i < strs.size(); ++i)\n        {\n            string s = strs[i];\n            sort(s.begin(), s.end());\n            MAP::iterator it = anagram.find(s);\n            if (it == anagram.end()) \n            {\n                anagram[s] = i;\n            } \n            else \n            {\n                if (it->second >= 0) {\n                    res.push_back(strs[it->second]);\n                    it->second = -1;\n                }\n                res.push_back(strs[i]);\n            }\n        }\n        return res;\n    }\n};"
  },
  {
    "path": "BalancedBinaryTree.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com : King, higuige@gmail.com\n Date:       Apr 10, 2013\n Update:     Oct 07, 2014\n Problem:    Balanced Binary Tree\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_110\n Notes:\n Given a binary tree, determine if it is height-balanced.\n For this problem, a height-balanced binary tree is defined as a binary tree in which \n the depth of the two subtrees of every node never differ by more than 1.\n\n Solution: DFS.\n */\n\n/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    bool isBalanced(TreeNode *root) {\n        return solve(root) != -1;\n    }\n    int solve(TreeNode *root) {\n        if (root == NULL) return 0;\n        int left = solve(root->left);\n        int right = solve(root->right);\n        if (left == -1 || right == -1 || abs(left - right) > 1) return -1;\n        return max(left,right) + 1;\n    }\n};\n"
  },
  {
    "path": "BestTimetoBuyandSellStock.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com : King, higuige@gmail.com\n Date:       Apr 28, 2013\n Update:     Oct 07, 2014\n Problem:    Best Time to Buy and Sell Stock\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_121\n Notes:\n Say you have an array for which the ith element is the price of a given stock on day i.\n If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), \n design an algorithm to find the maximum profit.\n\n Solution: For each element, calculate the max difference with the former elements.\n */\n\nclass Solution {\npublic:\n    int maxProfit(vector<int> &prices) {\n        int size = prices.size();\n        if (prices.empty()) return 0;\n        int minVal = prices[0], res = 0;\n        for (int i = 1; i < size; ++i)\n        {\n            minVal = min(minVal, prices[i]);\n            res = max(res, prices[i] - minVal);\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "BestTimetoBuyandSellStockII.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 28, 2013\n Problem:    Best Time to Buy and Sell Stock II\n Difficulty: Medium\n Source:     http://leetcode.com/onlinejudge#question_122\n Notes:\n Say you have an array for which the ith element is the price of a given stock on day i.\n Design an algorithm to find the maximum profit. You may complete as many transactions as you like \n (ie, buy one and sell one share of the stock multiple times). \n However, you may not engage in multiple transactions at the same time \n (ie, you must sell the stock before you buy again).\n\n Solution: 1. At the beginning of the ascending order: buy.\n              At the ending of the ascending order: sell.\n           2. For ascending order [1,2,4], (4 - 1) == (2 - 1) + (4 - 2).\n */\n\nclass Solution {\npublic:\n    int maxProfit(vector<int> &prices) {\n        return maxProfit_2(prices);\n    }\n    int maxProfit_1(vector<int> &prices) {\n        int res = 0;\n        int buy_i = -1;\n        for (int i = 1; i < prices.size(); ++i)\n        {\n            if (prices[i] > prices[i-1] && buy_i == -1)\n            {\n                buy_i = i - 1;\n            }\n            else if (prices[i] < prices[i -1] && buy_i != -1)\n            {\n                res += prices[i-1] - prices[buy_i];\n                buy_i = -1;\n            }\n        }\n        if (buy_i != -1)\n            res += prices[prices.size() - 1] - prices[buy_i];\n        return res;\n    }\n\n    int maxProfit_2(vector<int> &prices) {\n        int res = 0;\n        for (int i = 1; i < prices.size(); ++i)\n            if (prices[i] > prices[i-1])\n                res += prices[i] - prices[i-1];\n        return res;\n    }\n};\n"
  },
  {
    "path": "BestTimetoBuyandSellStockIII.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 28, 2013\n Update:     Aug 22, 2013\n Problem:    Best Time to Buy and Sell Stock III\n Difficulty: Medium\n Source:     http://leetcode.com/onlinejudge#question_123\n Notes:\n Say you have an array for which the ith element is the price of a given stock on day i.\n Design an algorithm to find the maximum profit. You may complete at most two transactions.\n Note:\n You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).\n\n Solution: dp. max profit =  max { l2r[0...i] + r2l[i+1...N-1] }.\n                         0 <= i <= N-1\n */\n\nclass Solution {\npublic:\n    int maxProfit(vector<int> &prices) {\n        int N = prices.size();\n        if (N <= 1) return 0;\n        \n        int l2r[N], r2l[N];\n        l2r[0] = 0;\n        r2l[N-1] = 0;\n        \n        int minn = prices[0];\n        for (int i = 1; i < N; ++i)\n        {\n            minn = min(minn, prices[i]);\n            l2r[i] = max(l2r[i-1], prices[i] - minn);\n        }\n        \n        int maxx = prices[N-1];\n        for (int i = N-2; i >= 0; --i)\n        {\n            maxx = max(maxx, prices[i]);\n            r2l[i] = max(r2l[i+1], maxx - prices[i]);\n        }\n        \n        int res = l2r[N-1];\n        for (int i = 0; i < N-1; ++i)\n            res = max(res, l2r[i] + r2l[i+1]);\n        return res;\n    }\n};\n"
  },
  {
    "path": "BinarySearchTreeIterator.h",
    "content": "/*\n Author:     king, wangjingui@outlook.com\n Date:       Dec 29, 2014\n Problem:    Binary Search Tree Iterator \n Difficulty: Easy\n Source:     https://oj.leetcode.com/problems/binary-search-tree-iterator/\n Notes:\n Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.\n\n Calling next() will return the next smallest number in the BST.\n\n Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.\n\n Solution: 1. Inorder traversal use stack.\n           2. Morris Inorder Traversal.\n */\n\n/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass BSTIterator_1 {\npublic:\n    BSTIterator(TreeNode *root) {\n        node = root;\n    }\n\n    /** @return whether we have a next smallest number */\n    bool hasNext() {\n        if (stk.empty() == true && node == NULL) return false;\n        return true;\n    }\n\n    /** @return the next smallest number */\n    int next() {\n        if (stk.empty() == true && node == NULL) return 0;\n        while (node != NULL) {\n            stk.push(node);\n            node = node->left;\n        }\n        int res = 0;\n        node = stk.top();\n        stk.pop();\n        res = node->val;\n        node = node->right;\n        return res;\n    }\nprivate:\n    TreeNode * node;\n    stack<TreeNode*> stk;\n};\n\nclass BSTIterator_2 {\npublic:\n    BSTIterator(TreeNode *root) {\n        node = root;\n    }\n\n    /** @return whether we have a next smallest number */\n    bool hasNext() {\n        return node != NULL;\n    }\n\n    /** @return the next smallest number */\n    int next() {\n        if (node == NULL) return 0;\n        int res = 0;\n        while (node != NULL) {\n            if (node->left == NULL) {\n                res = node->val;\n                node = node->right;\n                return res;\n            }\n            TreeNode * pre = node->left;\n            while (pre->right != NULL && pre->right != node) \n                pre = pre->right;\n            if (pre->right == NULL) {\n                pre->right = node;\n                node = node->left;\n            } else {\n                res = node->val;\n                node = node->right;\n                pre->right = NULL;\n                return res;\n            }\n        }\n        return res;\n    }\nprivate:\n    TreeNode * node;\n};\n/**\n * Your BSTIterator will be called like this:\n * BSTIterator i = BSTIterator(root);\n * while (i.hasNext()) cout << i.next();\n */"
  },
  {
    "path": "BinaryTreeInorderTraversal.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 22, 2013\n Update:     Aug 18, 2013\n Problem:    Binary Tree Inorder Traversal\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_94\n Notes:\n Given a binary tree, return the inorder traversal of its nodes' values.\n For example:\n Given binary tree {1,#,2,3},\n 1\n  \\\n   2\n  /\n 3\n return [1,3,2].\n Note: Recursive solution is trivial, could you do it iteratively?\n\n Solution: 1. Iterative way (stack).   Time: O(n), Space: O(n).\n           2. Recursive solution.      Time: O(n), Space: O(n).\n           3. Threaded tree (Morris).  Time: O(n), Space: O(1).\n */\n/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    vector<int> inorderTraversal(TreeNode *root) {\n        return inorderTraversal_1(root);\n    }\n    \n    vector<int> inorderTraversal_1(TreeNode *root) {\n        vector<int> res;\n        stack<TreeNode *> stk;\n        TreeNode *cur = root;\n        while (cur || !stk.empty())\n        {\n            if (cur)\n            {\n                stk.push(cur);\n                cur = cur->left;\n            }\n            else if (!stk.empty())\n            {\n                res.push_back(stk.top()->val);\n                cur = stk.top()->right;\n                stk.pop();\n            }\n        }\n        return res;\n    }\n    \n    vector<int> inorderTraversal_2(TreeNode *root) {\n        vector<int> res;\n        inorderTraversalRe(root, res);\n        return res;\n    }\n\n    void inorderTraversalRe(TreeNode *node, vector<int> &res) {\n        if (!node) return;\n        inorderTraversalRe(node->left, res);\n        res.push_back(node->val);\n        inorderTraversalRe(node->right, res);\n    }\n    \n    vector<int> inorderTraversal_3(TreeNode *root) {\n        vector<int> res;\n        TreeNode *cur = root;\n        while (cur)\n        {\n            if (cur->left)\n            {\n                TreeNode *prev = cur->left;\n                while (prev->right && prev->right != cur)\n                    prev = prev->right;\n                    \n                if (prev->right == cur)\n                {\n                    res.push_back(cur->val);\n                    cur = cur->right;\n                    prev->right = NULL;\n                }\n                else\n                {\n                    prev->right = cur;\n                    cur = cur->left;\n                }\n            }\n            else\n            {\n                res.push_back(cur->val);\n                cur = cur->right;\n            }\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "BinaryTreeLevelOrderTraversal.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 6, 2013\n Update:     Aug 15, 2013\n Problem:    Binary Tree Level Order Traversal\n Difficulty: easy\n Source:     http://leetcode.com/onlinejudge#question_102\n Notes:\n Given a binary tree, return the level order traversal of its nodes' values. \n (ie, from left to right, level by level).\n\n For example:\n Given binary tree {3,9,20,#,#,15,7},\n    3\n   / \\\n  9  20\n    /  \\\n   15   7\n return its level order traversal as:\n [\n  [3],\n  [9,20],\n  [15,7]\n ]\n \n Solution: 1. Use queue. In order to seperate the levels, use 'NULL' as the end indicator of one level.\n           2. DFS.\n */\n\n/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    vector<vector<int>> levelOrder(TreeNode *root) {\n        return levelOrder_1(root);\n    }\n    \n    vector<vector<int> > levelOrder_1(TreeNode *root) {\n        vector<vector<int> > res;\n        if (!root) return res;\n        queue<TreeNode *> q;\n        q.push(root);\n        q.push(NULL);\n        vector<int> level;\n        while (true)\n        {\n            TreeNode *node = q.front(); q.pop();\n            if (!node)\n            {\n                res.push_back(level);\n                level.clear();\n                if (q.empty()) break; // end\n                q.push(NULL);\n            }\n            else\n            {\n                level.push_back(node->val);\n                if (node->left) q.push(node->left);\n                if (node->right) q.push(node->right);\n            }\n        }\n        return res;\n    }\n    \n    vector<vector<int>> levelOrder_2(TreeNode *root) {\n        vector<vector<int>> res;\n        levelOrderRe(root, 0, res);\n        return res;\n    }\n\n    void levelOrderRe(TreeNode *node, int level, vector<vector<int>> &res)\n    {\n        if (!node) return;\n        if (res.size() <= level) res.push_back(vector<int>());\n        res[level].push_back(node->val);\n        levelOrderRe(node->left, level + 1, res);\n        levelOrderRe(node->right, level + 1, res);\n    }\n};\n"
  },
  {
    "path": "BinaryTreeLevelOrderTraversalII.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 7, 2013\n Problem:    Binary Tree Level Order Traversal II\n Difficulty: easy\n Source:     http://leetcode.com/onlinejudge#question_107\n Notes:\n Given a binary tree, return the bottom-up level order traversal of its nodes' values. \n (ie, from left to right, level by level from leaf to root).\n\n For example:\n Given binary tree {3,9,20,#,#,15,7},\n    3\n   / \\\n  9  20\n    /  \\\n   15   7\n return its bottom-up level order traversal as:\n [\n  [15,7]\n  [9,20],\n  [3],\n ]\n \n Solution: Queue version. On the basis of 'Binary Tree Level Order Traversal', reverse the final vector.\n */\n\n/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    vector<vector<int> > levelOrderBottom(TreeNode *root) {\n        vector<vector<int>> root2leaf;\n        queue<TreeNode *> q;\n        if (!root) return root2leaf;\n        q.push(root);\n        q.push(NULL);   // end indicator of one level\n        vector<int> level;\n        while (true)\n        {\n            TreeNode *node = q.front(); q.pop();\n            if (node)\n            {\n                level.push_back(node->val);\n                if (node->left) q.push(node->left);\n                if (node->right) q.push(node->right);\n            }\n            else\n            {\n                root2leaf.push_back(level);\n                level.clear();\n                if (q.empty()) break;    // CAUTIOUS! infinite loop\n                q.push(NULL);\n            }\n        }\n    \t// reverse\n        reverse(root2leaf.begin(), root2leaf.end());\n        return root2leaf;\n    }\n};"
  },
  {
    "path": "BinaryTreeMaximumPathSum.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com : King, higuige@gmail.com\n Date:       Apr 28, 2013\n Update:     Oct 07, 2014\n Problem:    Binary Tree Maximum Path Sum\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_124\n Notes:\n Given a binary tree, find the maximum path sum.\n The path may start and end at any node in the tree.\n For example:\n Given the below binary tree,\n   1\n  / \\\n 2   3\n Return 6.\n\n Solution: Recursion...\n */\n\n/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    int maxPathSum(TreeNode *root) {\n        int res = INT_MIN;\n        maxPathSumRe(root, res);\n        return res;\n    }\n\n    int maxPathSumRe(TreeNode *node, int &res)\n    {\n        if (!node) return 0;\n        int l = maxPathSumRe(node->left, res);\n        int r = maxPathSumRe(node->right, res);\n        int sum = max(node->val, max(l, r) + node->val);\n        res = max(res, max(0, l) + max(0, r) + node->val);\n        return sum;\n    }\n};\n"
  },
  {
    "path": "BinaryTreePostorderTraversal.h",
    "content": "/*\n Author:     Matthew Jin, marthew777@gmail.com\n Co-author:  Annie Kim, anniekim.pku@gmail.com : King, higuige@gmail.com\n Date:       Feb 21, 2014\n Update:     Nov 20, 2014\n Problem:    Binary Tree Postorder Traversal \n Difficulty: Easy\n Source:     http://oj.leetcode.com/problems/binary-tree-postorder-traversal/\n Notes:\n Given a binary tree, return the postorder traversal of its nodes' values.\n\n For example:\n Given binary tree {1,#,2,3},\n    1\n     \\\n      2\n     /\n    3\n return [3,2,1].\n\n Note: Recursive solution is trivial, could you do it iteratively?\n\n Solution: 1. Iterative way (stack).   Time: O(n), Space: O(n).\n           2. Recursive solution.      Time: O(n), Space: O(n).\n           3. Threaded tree (Morris).  Time: O(n), Space: O(1). \n              You may refer to my blog for more detailed explanations: \n              http://www.cnblogs.com/AnnieKim/archive/2013/06/15/MorrisTraversal.html\n           4. Recursive solution#2. transform into preorder traversal and reverse.\n           5. Threaded tree (Morris). Time: O(n), Space: O(logn);\n*/\n\n/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\n \nclass Solution {\npublic:\n    vector<int> postorderTraversal(TreeNode *root) {\n        return postorderTraversal_1(root);\n    }\n    \n    vector<int> postorderTraversal_1(TreeNode *root) {\n        vector<int> res;\n        stack<TreeNode *> stk;\n        TreeNode *last = NULL, *cur = root;\n        while(cur || !stk.empty()){\n            if (cur) {\n                stk.push(cur);\n                cur = cur->left;\n            }\n            else{\n                TreeNode *peak = stk.top();\n                if(peak->right && last != peak->right)\n                    cur = peak->right;\n                else{\n                    res.push_back(peak->val); \n                    stk.pop();\n                    last = peak;\n                }\n            }\n        }\n        return res;\n    }\n    \n    vector<int> postorderTraversal_2(TreeNode *root) {\n        vector<int> res;\n        postorderTraversalRe(root, res);\n        return res;\n    }\n\n    void postorderTraversalRe(TreeNode *node, vector<int> &res) {\n        if (!node) return;\n        postorderTraversalRe(node->left, res);\n        postorderTraversalRe(node->right, res);\n        res.push_back(node->val);\n    }\n    \n    vector<int> postorderTraversal_3(TreeNode *root) {\n        vector<int> res;\n        TreeNode dump(0);\n        dump.left = root;\n        TreeNode *cur = &dump, *prev = NULL;\n        while (cur)\n        {\n            if (cur->left == NULL)\n            {\n                cur = cur->right;\n            }\n            else\n            {\n                prev = cur->left;\n                while (prev->right != NULL && prev->right != cur)\n                    prev = prev->right;\n\n                if (prev->right == NULL)\n                {\n                    prev->right = cur;\n                    cur = cur->left;\n                }\n                else\n                {\n                    printReverse(cur->left, prev, res);  // call print\n                    prev->right = NULL;\n                    cur = cur->right;\n                }\n            }\n        }\n        return res;\n    }\n\n    void printReverse(TreeNode* from, TreeNode *to, vector<int>& res) // print the reversed tree nodes 'from' -> 'to'.\n    {\n        reverse(from, to);\n        \n        TreeNode *p = to;\n        while (true)\n        {\n            res.push_back(p->val);\n            if (p == from)\n                break;\n            p = p->right;\n        }\n        \n        reverse(to, from);\n    }\n    \n    void reverse(TreeNode *from, TreeNode *to) // reverse the tree nodes 'from' -> 'to'.\n    {\n        if (from == to)\n            return;\n        TreeNode *x = from, *y = from->right, *z;\n        while (true)\n        {\n            z = y->right;\n            y->right = x;\n            x = y;\n            y = z;\n            if (x == to)\n                break;\n        }\n    }\n\n    vector<int> postorderTraversal_4(TreeNode *root) {\n        vector<int>res;\n        stack<TreeNode *> s;\n        if (root == NULL) return res;\n        \n        dfs(root, res);\n        reverse(res.begin(), res.end());\n        return res;\n    }\n    void dfs(TreeNode * root, vector<int> & res) {\n        if (root == NULL) return;\n        res.push_back(root->val);\n        dfs(root->right, res);\n        dfs(root->left, res);\n    }\n\n    vector<int> postorderTraversal_5(TreeNode *root) {\n        vector<int>res;\n        stack<TreeNode *> s;\n        if (root == NULL) return res;\n        TreeNode dummy(-1);\n        dummy.left = root;\n        TreeNode * cur = &dummy;\n        while (cur) {\n            if(cur->left == NULL) {\n                cur = cur->right;\n            } else {\n                TreeNode * node = cur->left;\n                while (node->right && node->right != cur) {\n                    node = node->right;\n                }\n                if (node->right == NULL) {\n                    node->right = cur;\n                    cur = cur->left;\n                } else {\n                    // reverse push into res\n                    vector<int> tmp;\n                    TreeNode * it = cur->left;\n                    while(it != node) {\n                        tmp.push_back(it->val);\n                        it = it->right;\n                    }\n                    tmp.push_back(node->val);\n                    for(vector<int>::reverse_iterator iter = tmp.rbegin(); iter != tmp.rend(); ++iter) {\n                        res.push_back(*iter);\n                    }\n                    node->right = NULL;\n                    cur = cur->right;\n                }\n            }\n        }\n        \n        return res;\n    }\n};\n"
  },
  {
    "path": "BinaryTreePreorderTraversal.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Nov 11, 2013\n Problem:    Binary Tree Preorder Traversal\n Difficulty: Easy\n Source:     http://oj.leetcode.com/problems/binary-tree-preorder-traversal/\n Notes:\n Given a binary tree, return the preorder traversal of its nodes' values.\n For example:\n Given binary tree {1,#,2,3},\n    1\n     \\\n      2\n     /\n    3\n return [1,2,3].\n Note: Recursive solution is trivial, could you do it iteratively?\n\n Solution: 1. Iterative way (stack).   Time: O(n), Space: O(n).\n           2. Recursive solution.      Time: O(n), Space: O(n).\n           3. Threaded tree (Morris).  Time: O(n), Space: O(1).\n */\n/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    vector<int> preorderTraversal(TreeNode *root) {\n        return preorderTraversal_3(root);\n    }\n    \n    vector<int> preorderTraversal_1(TreeNode *root) {\n        vector<int> res;\n        stack<TreeNode *> stk;\n        TreeNode *cur = root;\n        while (cur || !stk.empty())\n        {\n            if (cur)\n            {\n                res.push_back(cur->val);\n                stk.push(cur);\n                cur = cur->left;\n            }\n            else if (!stk.empty())\n            {\n                cur = stk.top()->right;\n                stk.pop();\n            }\n        }\n        return res;\n    }\n    \n    vector<int> preorderTraversal_2(TreeNode *root) {\n        vector<int> res;\n        preorderTraversalRe(root, res);\n        return res;\n    }\n\n    void preorderTraversalRe(TreeNode *node, vector<int> &res) {\n        if (!node) return;\n        res.push_back(node->val);\n        preorderTraversalRe(node->left, res);\n        preorderTraversalRe(node->right, res);\n    }\n    \n    vector<int> preorderTraversal_3(TreeNode *root) {\n        vector<int> res;\n        TreeNode *cur = root;\n        while (cur)\n        {\n            if (cur->left)\n            {\n                TreeNode *prev = cur->left;\n                while (prev->right && prev->right != cur)\n                    prev = prev->right;\n                    \n                if (prev->right == cur)\n                {\n                    cur = cur->right;\n                    prev->right = NULL;\n                }\n                else\n                {\n                    res.push_back(cur->val);\n                    prev->right = cur;\n                    cur = cur->left;\n                }\n            }\n            else\n            {\n                res.push_back(cur->val);\n                cur = cur->right;\n            }\n        }\n        return res;\n    }\n};"
  },
  {
    "path": "BinaryTreeZigzagLevelOrderTraversal.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       May 16, 2013\n Update:     Sep 12, 2013\n Problem:    Binary Tree Zigzag Level Order Traversal\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_103\n Notes:\n Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left \n to right, then right to left for the next level and alternate between).\n For example:\n Given binary tree {3,9,20,#,#,15,7},\n     3\n    / \\\n   9  20\n  / \\\n 15  7\n return its zigzag level order traversal as:\n [\n  [3],\n  [20,9],\n  [15,7]\n ]\n\n Solution: 1. Queue + reverse.\n           2. Two stacks.\n           3. Vector. Contributed by yinlinglin.\n */\n\n/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\n\nclass Solution {\npublic:\n    vector<vector<int>> zigzagLevelOrder(TreeNode *root) {\n        return zigzagLevelOrder_1(root);\n    }\n    \n    // solution 1: Queue + Reverse.\n    vector<vector<int>> zigzagLevelOrder_1(TreeNode *root) {\n        vector<vector<int>> res;\n        if (!root) return res;\n        queue<TreeNode *> q;\n        q.push(root);\n        q.push(NULL);   // end indicator of one level\n        bool left2right = true;\n        vector<int> level;\n        while (true)\n        {\n            TreeNode *node = q.front(); q.pop();\n            if (node)\n            {\n                level.push_back(node->val);\n                if (node->left) q.push(node->left);\n                if (node->right) q.push(node->right);\n            }\n            else\n            {\n                if (!left2right) \n                    reverse(level.begin(), level.end());\n                res.push_back(level);\n                level.clear();\n                if (q.empty()) break;\n                q.push(NULL);\n                left2right = !left2right;\n            }\n        }\n        return res;\n    }\n    \n    // Solution 2: Two stacks.\n    vector<vector<int>> zigzagLevelOrder_2(TreeNode *root) {\n        vector<vector<int>> res;\n        if (!root) return res;\n        stack<TreeNode *> stk[2];\n        bool left2right = true;\n        int cur = 1, last = 0;\n        stk[last].push(root);\n        vector<int> level;\n        while (!stk[last].empty())\n        {\n            TreeNode *node = stk[last].top(); \n            stk[last].pop();\n            if (node)\n            {\n                level.push_back(node->val);\n                if (left2right)\n                {\n                    stk[cur].push(node->left);\n                    stk[cur].push(node->right);\n                }\n                else\n                {\n                    stk[cur].push(node->right);\n                    stk[cur].push(node->left);\n                }\n            }\n            if (stk[last].empty())\n            {\n                if (!level.empty())\n                    res.push_back(level);\n                level.clear();\n                swap(cur, last);\n                left2right = !left2right;\n            }\n        }\n        return res;\n    }\n    \n    // Solution 3: Vector. Contributed by yinlinglin.\n    // Compared to solution 1&2, this solution costs a little more space.\n    // This solution uses only one single vector instead of two stacks in solution 2.\n    vector<vector<int>> zigzagLevelOrder_3(TreeNode *root) {\n        vector<vector<int>> result;\n        if(!root) return result;\n        vector<TreeNode*> v;\n        v.push_back(root);\n        bool left2right = true;\n        int begin = 0, end = 0;\n        while(begin <= end)\n        {\n            vector<int> row;\n            for (int i = end; i >= begin; --i)\n            {\n                if (!v[i]) continue;\n                row.push_back(v[i]->val);\n                if(left2right)\n                {\n                    v.push_back(v[i]->left);\n                    v.push_back(v[i]->right);\n                }\n                else\n                {\n                    v.push_back(v[i]->right);\n                    v.push_back(v[i]->left);\n                }\n            }\n            if (!row.empty())\n                result.push_back(row);\n            begin = end + 1;\n            end = v.size() - 1;\n            left2right = !left2right;\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "Candy.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com, King, wangjingui@outlook.com\n Date:       Oct 3, 2013\n Update:     Dec 12, 2014\n Problem:    Candy\n Difficulty: Easy\n Source:     https://oj.leetcode.com/problems/candy/\n Notes:\n There are N children standing in a line. Each child is assigned a rating value.\n You are giving candies to these children subjected to the following requirements:\n - Each child must have at least one candy.\n - Children with a higher rating get more candies than their neighbors.\n What is the minimum candies you must give?\n\n Solution: You may refer to https://github.com/AnnieKim/ITint5/blob/master/031_%E5%88%86%E9%85%8D%E7%B3%96%E6%9E%9C.cpp\n           1. traverse only once with O(1) space. 2. O(n) space.\n           3. recursion + memo.\n*/\n\nclass Solution {\npublic:\n    int candy(vector<int> &ratings) {\n        return candy_1(ratings);\n    }\n    \n    int candy_1(vector<int> &ratings) {\n        int N = ratings.size();\n        if (N == 0) return 0;\n        int candy = 1, res = 1;\n        int maxValue = 1, maxIndex = 0;\n        for (int i = 1; i < N; ++i)\n        {\n            if (ratings[i] >= ratings[i-1]) \n            {\n                candy = ratings[i] == ratings[i-1] ? 1 : candy + 1;\n                maxValue = candy;\n                maxIndex = i;\n            }\n            else\n            {\n                if (candy == 1) {\n                    if (maxValue <= i - maxIndex) {\n                        res += i - maxIndex;\n                        maxValue++;\n                    } else {\n                        res += i - maxIndex - 1;\n                    }\n                }\n                candy = 1;\n            }\n            res += candy;\n        }\n        return res;\n    }\n    \n    int candy_2(vector<int> &ratings) {\n        int N = ratings.size();\n        if (N == 0) return 0;\n        int candy[N];\n        for (int i = 0; i < N; ++i)\n            candy[i] = 1;\n        for (int i = 1; i < N; ++i)\n            if (ratings[i] > ratings[i-1])\n                candy[i] = candy[i-1] + 1;\n        for (int i = N-2; i >= 0; --i)\n            if (ratings[i] > ratings[i+1] && candy[i] <= candy[i+1])\n                candy[i] = candy[i+1] + 1;\n        int res = 0;\n        for (int i = 0; i < N; ++i)\n            res += candy[i];\n        return res;\n    }\n    int dfs(const vector<int>& ratings, vector<int>& dp, int i)\n    {\n        if (dp[i] != -1) return dp[i];\n        dp[i] = 1;\n        if(i > 0  && ratings[i] > ratings[i-1])\n            dp[i] = max(dp[i], dfs(ratings, dp, i-1) + 1);\n        if(i < ratings.size()-1 && ratings[i] > ratings[i+1])\n            dp[i] = max(dp[i], dfs(ratings, dp, i+1) + 1);\n        return dp[i];\n    }\n    int candy_3(vector<int>& ratings)\n    {\n        vector<int> dp(ratings.size(), -1);\n        int res = 0;\n        for(int i = 0;i < ratings.size(); ++i)\n            res += dfs(ratings, dp, i);\n        return res;\n    }\n};"
  },
  {
    "path": "ClimbingStairs.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       May 8, 2013\n Problem:    Climbing Stairs\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_70\n Notes:\n You are climbing a stair case. It takes n steps to reach to the top.\n Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?\n\n Solution: Clime one step from last stair or clime 2 steps from the last last stair.\n */\n\nclass Solution {\npublic:\n    int climbStairs(int n) {\n        int last = 1;\n        int lastlast = 1;\n        for (int i = 2; i <= n; i++)\n        {\n            int step = last + lastlast;\n            lastlast = last;\n            last = step;\n        }\n        return last;\n    }\n};"
  },
  {
    "path": "CloneGraph.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Sep 26, 2013\n Problem:    Clone Graph\n Difficulty: Easy\n Source:     http://oj.leetcode.com/problems/clone-graph/\n Notes:\n Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.\n \n OJ's undirected graph serialization:\n Nodes are labeled from 0 to N - 1, where N is the total nodes in the graph.\n We use # as a separator for each node, and , as a separator for each neighbor of the node.\n As an example, consider the serialized graph {1,2#2#2}.\n The graph has a total of three nodes, and therefore contains three parts as separated by #.\n Connect node 0 to both nodes 1 and 2.\n Connect node 1 to node 2.\n Connect node 2 to node 2 (itself), thus forming a self-cycle.\n Visually, the graph looks like the following:\n\n       1\n      / \\\n     /   \\\n    0 --- 2\n         / \\\n         \\_/\n\n Solution: 1. DFS. 2. BFS.\n */\n\n/**\n * Definition for undirected graph.\n * struct UndirectedGraphNode {\n *     int label;\n *     vector<UndirectedGraphNode *> neighbors;\n *     UndirectedGraphNode(int x) : label(x) {};\n * };\n */\nclass Solution {\npublic:\n    typedef UndirectedGraphNode GraphNode;\n    typedef unordered_map<GraphNode *, GraphNode *> MAP;\n    \n    GraphNode *cloneGraph(GraphNode *node) {\n        return cloneGraph_1(node);\n    }\n    \n    // DFS\n    GraphNode *cloneGraph_1(GraphNode *node) {\n        MAP map;\n        return cloneGraphRe(node, map);\n    }\n    \n    GraphNode *cloneGraphRe(GraphNode *node, MAP &map) {\n        if (!node) return NULL;\n        if (map.find(node) != map.end())\n            return map[node];\n        GraphNode *newNode = new GraphNode(node->label);\n        map[node] = newNode;\n        for (int i = 0; i < node->neighbors.size(); ++i)\n            newNode->neighbors.push_back(cloneGraphRe(node->neighbors[i], map));\n        return newNode;\n    }\n    \n    // BFS\n    UndirectedGraphNode *cloneGraph_2(UndirectedGraphNode *node) {\n        if (node == nullptr) {\n            return nullptr;\n        }\n        unordered_map<UndirectedGraphNode*, UndirectedGraphNode*> nodesMap;\n        nodesMap[node] = new UndirectedGraphNode(node->label);\n        queue<UndirectedGraphNode*> q;\n        q.push(node);\n        while (!q.empty()) {\n            UndirectedGraphNode* tmp = q.front();\n            q.pop();\n            for (int i = 0; i < tmp->neighbors.size(); ++i) {\n                UndirectedGraphNode* neighbor = tmp->neighbors[i];\n                if (nodesMap.find(neighbor) == nodesMap.end()) {\n                    UndirectedGraphNode* newNode = new UndirectedGraphNode(neighbor->label);\n                    nodesMap[neighbor] = newNode;\n                    q.push(neighbor);\n                }\n                nodesMap[tmp]->neighbors.push_back(nodesMap[neighbor]);\n            }\n        }\n        return nodesMap[node];\n    }\n};\n"
  },
  {
    "path": "CombinationSum.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       May 25, 2013\n Problem:    Combination Sum\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_39\n Notes:\n Given a set of candidate numbers (C) and a target number (T), find all unique \n combinations in C where the candidate numbers sums to T.\n The same repeated number may be chosen from C unlimited number of times.\n Note:\n All numbers (including target) will be positive integers.\n Elements in a combination (a1, a2, .. , ak) must be in non-descending order. (ie, a1 <= a2 <= ... <= ak).\n The solution set must not contain duplicate combinations.\n For example, given candidate set 2,3,6,7 and target 7, \n A solution set is: \n [7] \n [2, 2, 3] \n\n Solution: Sort & Recursion.\n*/\n\nclass Solution {\npublic:\n    vector<vector<int>> combinationSum(vector<int> &candidates, int target) {\n        vector<vector<int>> res;\n        sort(candidates.begin(), candidates.end());\n        vector<int> com;\n        combinationSumRe(candidates, target, 0, com, res);\n        return res;\n    }\n\n    void combinationSumRe(const vector<int> &num, int target, int start, vector<int> &com, vector<vector<int>> &res)\n    {\n        if (target == 0) {\n            res.push_back(com);\n            return;\n        }\n        for (int i = start; i < num.size() && target >= num[i]; ++i) {\n            com.push_back(num[i]);\n            combinationSumRe(num, target-num[i], i, com, res);\n            com.pop_back();\n        }\n    }\n};"
  },
  {
    "path": "CombinationSumII.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       May 6, 2013\n Problem:    Combination Sum II\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_40\n Notes:\n Given a collection of candidate numbers (C) and a target number (T), find all unique combinations\n in C where the candidate numbers sums to T.\n Each number in C may only be used once in the combination.\n Note:\n All numbers (including target) will be positive integers.\n Elements in a combination (a1, a2, .. , ak) must be in non-descending order. (ie, a1 <= a2 <= ... <= ak).\n The solution set must not contain duplicate combinations.\n For example, given candidate set 10,1,2,7,6,1,5 and target 8, \n A solution set is: \n [1, 7] \n [1, 2, 5] \n [2, 6] \n [1, 1, 6] \n\n Solution: ..Similar to Combination Sum I, except for line 42 && 44.\n */\n\nclass Solution {\npublic:\n    vector<vector<int>> combinationSum2(vector<int> &num, int target) {\n        vector<vector<int>> res;\n        sort(num.begin(), num.end());\n        vector<int> com;\n        combinationSum2Re(num, target, 0, com, res);\n        return res;\n    }\n\n    void combinationSum2Re(const vector<int> &num, int target, int start, vector<int> &com, vector<vector<int>> &res)\n    {\n        if (target == 0) {\n            res.push_back(com);\n            return;\n        }\n        for (int i = start; i < num.size() && num[i] <= target; ++i) {\n            if (i > start && num[i] == num[i-1]) continue;\n            com.push_back(num[i]);\n            combinationSum2Re(num, target-num[i], i+1, com, res);\n            com.pop_back();\n        }\n    }\n};"
  },
  {
    "path": "Combinations.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       May 5, 2013\n Update:     Sep 28, 2013\n Problem:    Combinations\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_77\n Notes:\n Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.\n For example,\n If n = 4 and k = 2, a solution is:\n [\n    [2,4],\n    [3,4],\n    [2,3],\n    [1,2],\n    [1,3],\n    [1,4],\n ]\n\n Solution: DFS.\n */\n\nclass Solution {\npublic:\n    vector<vector<int> > combine(int n, int k) {\n        vector<vector<int> > res;\n        vector<int> com;\n        combineRe(n, k, 1, com, res);\n        return res;\n    }\n    \n    void combineRe(int n, int k, int start, vector<int> &com, vector<vector<int> > &res){\n        int m = com.size();\n        if (m == k) {\n            res.push_back(com);\n            return;\n        }\n        for (int i = start; i <= n-(k-m)+1; ++i) {\n            com.push_back(i);\n            combineRe(n, k, i+1, com, res);\n            com.pop_back();\n        }\n    }\n};"
  },
  {
    "path": "CompareVersionNumbers.h",
    "content": "/*\n Author:     King, wangjingui@outlook.com\n Date:       Dec 15, 2014\n Problem:    Compare Version Numbers\n Difficulty: Easy\n Source:     https://oj.leetcode.com/problems/compare-version-numbers/\n Notes:\n Compare two version numbers version1 and version1.\n If version1 > version2 return 1, if version1 < version2 return -1, otherwise return 0.\n\n You may assume that the version strings are non-empty and contain only digits and the . character.\n The . character does not represent a decimal point and is used to separate number sequences.\n For instance, 2.5 is not \"two and a half\" or \"half way to version three\", it is the fifth second-level revision of the second first-level revision.\n\n Here is an example of version numbers ordering:\n\n 0.1 < 1.1 < 1.2 < 13.37\n\n Solution: ...\n */\nclass Solution {\npublic:\n    int compareVersion(string version1, string version2) {\n        int v1len = version1.size(), v2len = version2.size();\n        for (int i = 0, j = 0; (i < v1len || j < v2len); ) {\n        \tlong long a = 0, b =0;\n        \twhile (i < v1len && version1[i] != '.') {\n        \t\ta = a * 10 + version1[i++] - '0';\n        \t}\n        \t++i;\n        \twhile (j < v2len && version2[j] != '.') {\n        \t\tb = b * 10 + version2[j++] - '0';\n        \t}\n        \t++j;\n        \tif (a > b) return 1;\n        \tif (a < b) return -1;\n        }\n    \treturn 0;\n    }\n};"
  },
  {
    "path": "ConstructBinaryTreefromInorderandPostorderTraversal.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       May 16, 2013\n Problem:    Construct Binary Tree from Inorder and Postorder Traversal\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_106\n Notes:\n Given inorder and postorder traversal of a tree, construct the binary tree.\n Note:\n You may assume that duplicates do not exist in the tree.\n\n Solution: Recursion.\n */\n\n/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {\n        int N = inorder.size();\n        return buildTreeRe(inorder.begin(), postorder.begin(), N);\n    }\n\n    TreeNode *buildTreeRe(vector<int>::iterator inorder, vector<int>::iterator postorder, int N) {\n        if (N <= 0) return NULL;\n        vector<int>::iterator it = find(inorder, inorder+N, *(postorder+N-1));\n        int pos = it - inorder;\n        TreeNode *root = new TreeNode(*(postorder+N-1));\n        root->left = buildTreeRe(inorder, postorder, pos);\n        root->right = buildTreeRe(inorder+pos+1, postorder+pos, N-pos-1);\n        return root;\n    }\n};"
  },
  {
    "path": "ConstructBinaryTreefromPreorderandInorderTraversal.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       May 16, 2013\n Problem:    Construct Binary Tree from Preorder and Inorder Traversal\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_105\n Notes:\n Given preorder and inorder traversal of a tree, construct the binary tree.\n Note:\n You may assume that duplicates do not exist in the tree.\n\n Solution: Recursion.\n */\n\n/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\n\nclass Solution {\npublic:\n    TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {\n        return buildTreeRe(preorder.begin(), inorder.begin(), preorder.size());\n    }\n\n    TreeNode *buildTreeRe(vector<int>::iterator preorder, vector<int>::iterator inorder, int N) {\n        if (N <= 0) return NULL;\n        vector<int>::iterator it = find(inorder, inorder + N, *preorder);\n        int pos = it - inorder;\n        TreeNode *root = new TreeNode(*preorder);\n        root->left = buildTreeRe(preorder+1, inorder, pos);\n        root->right = buildTreeRe(preorder+1+pos, inorder+pos+1, N-1-pos);\n        return root;\n    }\n};"
  },
  {
    "path": "ContainerWithMostWater.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 16, 2013\n Update:     Aug 22, 2013\n Problem:    Container With Most Water\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_11\n Notes:\n Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). \n n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). \n Find two lines, which together with x-axis forms a container, such that the container contains the most water.\n Note: You may not slant the container.\n\n Solution: From both sides to the center.\n*/\n\nclass Solution {\npublic:\n    int maxArea(vector<int> &height) {\n        int res = 0;\n        int l = 0, r = height.size()-1;\n        while (l < r)\n        {\n            if (height[l] <= height[r])\n            {\n                res = max(res, (r-l) * height[l]);\n                l++;\n            }\n            else\n            {\n                res = max(res, (r-l) * height[r]);\n                r--;\n            }\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "ConvertSortedArraytoBinarySearchTree.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 9, 2013\n Problem:    Convert Sorted Array to Binary Search Tree\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_108\n Notes:\n Given an array where elements are sorted in ascending order, convert it to a height balanced BST.\n\n Solution: Recursion.\n */\n\n/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    TreeNode *sortedArrayToBST(vector<int> &num) {\n        return buildBST(num, 0, num.size() - 1);\n    }\n    \n    TreeNode *buildBST(vector<int> &num, int start, int end)\n    {\n        if (start > end) return NULL;\n\n        int mid = (start + end) / 2;\n        TreeNode *root = new TreeNode(num[mid]);\n        root->left = buildBST(num, start, mid - 1);\n        root->right = buildBST(num, mid + 1, end);\n\n        return root;\n    }\n};"
  },
  {
    "path": "ConvertSortedListtoBinarySearchTree.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 10, 2013\n Update:     Jul 29, 2013\n Problem:    Convert Sorted List to Binary Search Tree\n Difficulty: Medium\n Source:     http://leetcode.com/onlinejudge#question_109\n Notes:\n Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.\n\n Solution: 1. Recursion. Pre-order. A very good Idea. O(n)\n           2. Recursion, Binary Search.\n */\n\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(int x) : val(x), next(NULL) {}\n * };\n */\n/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    TreeNode *sortedListToBST_1(ListNode *head) {\n        return sortedListToBSTRe(head, getLength(head));\n    }\n    \n    TreeNode *sortedListToBSTRe(ListNode *&head, int length)\n    {\n        if (length == 0) return NULL;\n        int mid = length / 2;\n        TreeNode *left = sortedListToBSTRe(head, mid);\n        TreeNode *root = new TreeNode(head->val);\n        TreeNode *right = sortedListToBSTRe(head->next, length - mid - 1);\n        root->left = left;\n        root->right = right;\n        head = head->next;\n        return root;\n    }\n    \n    int getLength(ListNode *head)\n    {\n        int length = 0;\n        while (head)\n        {\n            length++;\n            head = head->next;\n        }\n        return length;\n    }\n\n    TreeNode *sortedListToBST_2(ListNode *head) {\n        if(head==nullptr) return nullptr;\n        if(head->next==nullptr) return new TreeNode(head->val);\n        ListNode * slow = head;\n        ListNode * fast = head;\n        ListNode * pre = nullptr;\n        while(fast->next&&fast->next->next){\n            pre = slow;\n            slow = slow->next;\n            fast = fast->next->next;\n        }\n        fast = slow->next;\n        TreeNode * node = new TreeNode(slow->val);\n        if(pre){\n            pre->next = nullptr;\n            node->left = sortedListToBST(head);\n        }\n        node->right = sortedListToBST(fast);\n        return node;\n    }\n};\n"
  },
  {
    "path": "CopyListwithRandomPointer.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Oct 5, 2013\n Problem:    Copy List with Random Pointer\n Difficulty: Easy\n Source:     http://oj.leetcode.com/problems/copy-list-with-random-pointer/\n Notes:\n A linked list is given such that each node contains an additional random pointer \n which could point to any node in the list or null.\n Return a deep copy of the list.\n\n Solution: Solution 1 uses constant extra space.\n*/\n\n/**\n * Definition for singly-linked list with a random pointer.\n * struct RandomListNode {\n *     int label;\n *     RandomListNode *next, *random;\n *     RandomListNode(int x) : label(x), next(NULL), random(NULL) {}\n * };\n */\nclass Solution {\n    typedef unordered_map<RandomListNode*, RandomListNode*> nodemap;\npublic:\n    RandomListNode *copyRandomList(RandomListNode *head) {\n        return copyRandomList_1(head);\n    }\n    \n    RandomListNode *copyRandomList_1(RandomListNode *head) {\n        for (RandomListNode *cur = head; cur; cur = cur->next->next) {\n            RandomListNode *newNode = new RandomListNode(cur->label);\n            newNode->next = cur->next;\n            cur->next = newNode;\n        }\n        \n        for (RandomListNode *cur = head; cur; cur = cur->next->next)\n            if (cur->random)\n                cur->next->random = cur->random->next;\n        \n        RandomListNode dummy(0), *curNew = &dummy;\n        for (RandomListNode *cur = head; cur; cur = cur->next) {\n            curNew->next = cur->next;\n            curNew = curNew->next;\n            cur->next = cur->next->next;\n        }\n        return dummy.next;\n    }\n    \n    RandomListNode *copyRandomList_2(RandomListNode *head) {\n        if (!head) return NULL;\n        unordered_map<RandomListNode *, RandomListNode *> map;\n        RandomListNode dummy(0), *curNew = &dummy, *cur = head;\n        while (cur) \n        {\n            if (map.find(cur) == map.end())\n                map[cur] = new RandomListNode(cur->label);\n            if (cur->random && map.find(cur->random) == map.end())\n                map[cur->random] = new RandomListNode(cur->random->label);\n            curNew->next = map[cur];\n            curNew = curNew->next;\n            curNew->random = map[cur->random];\n            cur = cur->next;\n        }\n        return dummy.next;\n    }\n    RandomListNode *copyRandomList_3(RandomListNode *head) {\n        nodemap m;\n        return copy(head, m);\n    }\n    RandomListNode *copy(RandomListNode *root, nodemap &m) {\n        if (root == nullptr) return nullptr;\n        nodemap::iterator iter = m.find(root);\n        if (iter != m.end()) {\n            return m[root];\n        }\n        RandomListNode *node = new RandomListNode(root->label);\n        m[root] = node;\n        node->next = copy(root->next, m);\n        node->random = copy(root->random, m);\n        return node;   \n    }\n};\n"
  },
  {
    "path": "CountandSay.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 8, 2013\n Update:     Aug 10, 2013\n Problem:    Count and Say\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_38\n Notes:\n The count-and-say sequence is the sequence of integers beginning as follows:\n 1, 11, 21, 1211, 111221, ...\n\n 1 is read off as \"one 1\" or 11.\n 11 is read off as \"two 1s\" or 21.\n 21 is read off as \"one 2, then one 1\" or 1211.\n Given an integer n, generate the nth sequence.\n Note: The sequence of integers will be represented as a string.\n\n Solution: ...\n*/\n\nclass Solution {\npublic:\n    string countAndSay(int n) {\n        string res = \"1\";\n        for (int i = 2; i <= n; ++i)\n        {\n            stringstream ss;\n            int j = 0, N = res.size();\n            while (j < N) {\n                int k = j + 1;\n                while (k < N && res[k] == res[j])\n                    k++;\n                ss << (k - j) << res[j];\n                j = k;\n            }\n            ss >> res;\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "DecodeWays.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       May 20, 2013\n Problem:    Decode Ways\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_91\n Notes:\n A message containing letters from A-Z is being encoded to numbers using the following mapping:\n 'A' -> 1\n 'B' -> 2\n ...\n 'Z' -> 26\n Given an encoded message containing digits, determine the total number of ways to decode it.\n For example,\n Given encoded message \"12\", it could be decoded as \"AB\" (1 2) or \"L\" (12).\n The number of ways decoding \"12\" is 2.\n\n Solution: 1. dp. Note that '0' must be decoded in together with the number in front of it.\n           2. dp. Time : O(n); Space : O(1).\n */\n\nclass Solution {\npublic:\n    int numDecodings_1(string s) {\n        if (s.empty() || s[0] == '0') \n            return 0;\n        int N = s.size();\n        int dp[N+1];\n        dp[0] = 1;\n        dp[1] = 1;\n        for (int i = 1; i < N; ++i)\n        {\n            if (s[i] == '0')\n            {\n                if (s[i-1] != '1' && s[i-1] != '2')\n                    return 0;\n                dp[i+1] = dp[i-1];\n            }\n            else\n            {\n                int num = s[i] - '0' + (s[i-1] - '0') * 10;\n                if (num >= 11 && num <= 26)\n                    dp[i+1] = dp[i] + dp[i-1];\n                else\n                    dp[i+1] = dp[i];\n            }\n        }\n        return dp[N];\n    }\n    int numDecodings_2(string s) {\n        if (s.empty() || s[0] == '0') return 0;\n        int N = s.size();\n        int f0 = 1, f1 = 1;\n        for (int i = 1; i < N; ++i) {\n            if (s[i] == '0') f1 = 0;\n            int num = s[i] - '0' + (s[i-1] - '0') * 10;\n            if (num < 10 || num > 26) {\n                f0 = 0;\n            }\n            int tmp = f1;\n            f1 = f1 + f0;\n            f0 = tmp;\n        }\n        return f1;\n    }\n};"
  },
  {
    "path": "DistinctSubsequences.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com : King, higuige@gmail.com\n Date:       May 16, 2013\n Update:     Oct 07, 2014\n Problem:    Distinct Subsequences\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_115\n Notes:\n Given a string S and a string T, count the number of distinct subsequences of T in S.\n A subsequence of a string is a new string which is formed from the original string by deleting\n some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, \"ACE\" is a subsequence of \"ABCDE\" while \"AEC\" is not).\n\n Here is an example:\n S = \"rabbbit\", T = \"rabbit\"\n Return 3.\n\n Solution: dp.\n */\nclass Solution {\npublic:\n    int numDistinct(string S, string T) {\n        return numDistinct_2(S, T);\n    }\n    int numDistinct_1(string S, string T) {\n        int M = S.size();\n        int N = T.size();\n        vector<vector<int> > dp(M+1, vector<int>(N+1));\n        for (int j = 0; j <= N; ++j) {\n            dp[0][j] = 0;\n        }\n        for (int i = 0; i <= M; ++i) {\n            dp[i][0] = 1;\n        }\n        for (int i = 1; i <= M; ++i) {\n            for (int j = 1; j <= N; ++j) {\n                dp[i][j] = dp[i-1][j] + (S[i-1] == T[j-1] ? dp[i-1][j-1] : 0);\n            }\n        }\n        return dp[M][N];\n    }\n    int numDistinct_2(string S, string T) {\n        int M = S.size();\n        int N = T.size();\n        vector<int> dp(N + 1);\n        dp[0] = 1;\n        for (int i = 1; i <= M; ++i) {\n            for (int j = N; j >=1; --j) {\n                dp[j] = dp[j] + (S[i-1] == T[j-1] ? dp[j-1] : 0);\n            }\n        }\n        return dp[N];\n    }\n};"
  },
  {
    "path": "DivideTwoIntegers.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com : King, higuige@gmail.com\n Date:       Jul 8, 2013\n Update:     Nov 18, 2014\n Problem:    Divide Two Integers\n Difficulty: Medium\n Source:     https://oj.leetcode.com/problems/divide-two-integers/\n Notes:\n Divide two integers without using multiplication, division and mod operator.\n\n Solution: Use << operator.\n*/\n\nclass Solution {\npublic:\n    //Top -> Down\n    int divide_1(int dividend, int divisor) {\n        assert(divisor != 0);\n        bool flag = (dividend < 0) ^ (divisor < 0);\n        long long dividendll = abs((long long)dividend);\n        long long divisorll = abs((long long)divisor);\n        long long res = 0;\n        long long d = divisorll, q = 1;\n        while ((d << 1) <= dividendll) {\n            d <<= 1;\n            q <<= 1;\n        }\n        while (dividendll >= divisorll) {\n            if (dividendll >= d) {\n                dividendll -= d;\n                res += q;\n            }\n            d >>= 1;\n            q >>= 1;\n        }\n        if (flag == true) res = -res;\n        if (res > INT_MAX) return INT_MAX;\n        return res;\n    }\n    //bottom -> up\n    int divide(int dividend, int divisor) {\n        assert(divisor != 0);\n        bool flag = (dividend < 0) ^ (divisor < 0);\n        long long Dividend = abs((long long)dividend);\n        long long Divisor = abs((long long)divisor);\n        long long res = 0;\n        while (Dividend >= Divisor) {\n            long long c = Divisor;\n            for (int i = 0; (c << i) <= Dividend; ++i) {\n                Dividend -= (c << i);\n                res += (1 << i);\n            }\n        }\n        if (flag == true) res = -res;\n        if (res > INT_MAX) return INT_MAX;\n        return res;\n    }\n};"
  },
  {
    "path": "DungeonGame.h",
    "content": "/*\n Author:     King, wangjingui@outlook.com\n Date:       Jan 6, 2015\n Problem:    Dungeon Game\n Difficulty: Easy\n Source:     https://oj.leetcode.com/problems/dungeon-game/\n Notes:\n The demons had captured the princess (P) and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of M x N rooms laid out in a 2D grid. Our valiant knight (K) was initially positioned in the top-left room and must fight his way through the dungeon to rescue the princess.\n\n The knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies immediately.\n\n Some of the rooms are guarded by demons, so the knight loses health (negative integers) upon entering these rooms; other rooms are either empty (0's) or contain magic orbs that increase the knight's health (positive integers).\n\n In order to reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step.\n\n\n Write a function to determine the knight's minimum initial health so that he is able to rescue the princess.\n\n For example, given the dungeon below, the initial health of the knight must be at least 7 if he follows the optimal path RIGHT-> RIGHT -> DOWN -> DOWN.\n\n -2 (K)  -3  3\n -5  -10 1\n 10  30  -5 (P)\n\n Notes:\n\n The knight's health has no upper bound.\n Any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned.\n\n Solution: \n Fortunately, this problem can be solved through a table-filling Dynamic Programming technique, similar to other \"grid walking\" problems:\n\nTo begin with, we should maintain a 2D array D of the same size as the dungeon, where D[i][j] represents the minimum health that guarantees the survival of the knight for the rest of his quest BEFORE entering room(i, j). Obviously D[0][0] is the final answer we are after. Hence, for this problem, we need to fill the table from the bottom right corner to left top.\n\nThen, let us decide what the health should be at least when leaving room (i, j). There are only two paths to choose from at this point: (i+1, j) and (i, j+1). Of course we will choose the room that has the smaller D value, or in other words, the knight can finish the rest of his journey with a smaller initial health. Therefore we have:\n\n  min_HP_on_exit = min(D[i+1][j], D[i][j+1])\nNow D[i][j] can be computed from dungeon[i][j] and min_HP_on_exit based on one of the following situations:\n\nIf dungeon[i][j] == 0, then nothing happens in this room; the knight can leave the room with the same health he enters the room with, i.e. D[i][j] = min_HP_on_exit.\nIf dungeon[i][j] < 0, then the knight must have a health greater than min_HP_on_exit before entering (i, j) in order to compensate for the health lost in this room. The minimum amount of compensation is \"-dungeon[i][j]\", so we have D[i][j] = min_HP_on_exit - dungeon[i][j].\nIf dungeon[i][j] > 0, then the knight could enter (i, j) with a health as little as min_HP_on_exit - dungeon[i][j], since he could gain \"dungeon[i][j]\" health in this room. However, the value of min_HP_on_exit - dungeon[i][j] might drop to 0 or below in this situation. When this happens, we must clip the value to 1 in order to make sure D[i][j] stays positive: D[i][j] = max(min_HP_on_exit - dungeon[i][j], 1).\nNotice that the equation for dungeon[i][j] > 0 actually covers the other two situations. We can thus describe all three situations with one common equation, i.e.:\n\nD[i][j] = max(min_HP_on_exit - dungeon[i][j], 1)\nfor any value of dungeon[i][j].\n\nTake D[0][0] and we are good to go. Also, like many other \"table-filling\" problems, the 2D array D can be replaced with a 1D \"rolling\" array here.\n */\n\nclass Solution {\npublic:\n    int calculateMinimumHP(vector<vector<int> > &dungeon) {\n        int M = dungeon.size(), res = 0;\n        if (M == 0) return res;\n        int N = dungeon[0].size();\n        vector<vector<int>> dp(M, vector<int>(N,0));\n        dp[M-1][N-1] = 1 - min(0, dungeon[M-1][N-1]);\n        for (int i = M - 2; i >= 0; --i) {\n            if (dp[i+1][N-1] - dungeon[i][N-1] <= 0) dp[i][N-1] = 1;\n            else dp[i][N-1] = dp[i+1][N-1] - dungeon[i][N-1]; \n        }\n        for (int j = N - 2; j >= 0; --j) {\n            if (dp[M-1][j+1] - dungeon[M-1][j] <= 0) dp[M-1][j] = 1;\n            else dp[M-1][j] = dp[M-1][j+1] - dungeon[M-1][j];\n        }\n        for (int i = M - 2; i >= 0; --i) {\n            for (int j = N - 2; j >= 0; --j) {\n                int val = min(dp[i+1][j], dp[i][j+1]);\n                if (dungeon[i][j] >= val) dp[i][j] = 1;\n                else dp[i][j] = val - dungeon[i][j];\n            }\n        }\n        return max(1,dp[0][0]);\n    }\n};\n"
  },
  {
    "path": "EditDistance.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 7, 2013\n Update:     Sep 28, 2013\n Problem:    Edit Distance\n Difficulty: Medium\n Source:     http://leetcode.com/onlinejudge#question_72\n Notes:\n Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)\n You have the following 3 operations permitted on a word:\n a) Insert a character\n b) Delete a character\n c) Replace a character\n\n Solution: Dynamic Programming.\n           1. Time: O(mn) Space: O(mn)\n           2. Time: O(mn) Space: O(n);\n */\n\nclass Solution {\npublic:\n    int minDistance(string word1, string word2) {\n        return minDistance_2(word1, word2);\n    }\n    \n    int minDistance_1(string word1, string word2) {\n        int M = word1.size(), N = word2.size();\n        int dp[N+1][M+1];\n        for (int j = 0; j <= M; j++)\n            dp[0][j] = j;\n        for (int i = 0; i <= N; i++)\n            dp[i][0] = i;\n        for (int i = 1; i <= N; i++)\n            for (int j = 1; j <= M; j++)\n                if (word2[i-1] == word1[j-1])\n                    dp[i][j] = dp[i-1][j-1];\n                else\n                    dp[i][j] = min(dp[i-1][j-1], min(dp[i][j-1], dp[i-1][j])) + 1;\n        \n        return dp[N][M];\n    }\n    \n    int minDistance_2(string word1, string word2) {\n        int M = word1.size(), N = word2.size();\n        int dp[N+1];\n        for (int j = 0; j <= N; ++j)\n            dp[j] = j;\n        for (int i = 1; i <= M; ++i)\n        {\n            int upperLeftBackup = dp[0];\n            dp[0] = i;\n            for (int j = 1; j <= N; ++j)\n            {\n                int upperLeft = upperLeftBackup;\n                upperLeftBackup = dp[j];\n                if (word1[i-1] == word2[j-1])\n                    dp[j] = upperLeft;\n                else\n                    dp[j] = min(min(dp[j-1], dp[j]), upperLeft) + 1;\n            }\n        }\n        return dp[N];\n    }\n};"
  },
  {
    "path": "EvaluateReversePolishNotation.h",
    "content": "/*\n Author:     Matthew Jin, marthew777@gmail.com\n Date:       \n Problem:    Evaluate Reverse Polish Notation\n Difficulty: Easy\n Notes:\n Evaluate the value of an arithmetic expression in Reverse Polish Notation.\n Valid operators are +, -, *, /. Each operand may be an integer or another expression.\n Some examples:\n  [\"2\", \"1\", \"+\", \"3\", \"*\"] -> ((2 + 1) * 3) -> 9\n  [\"4\", \"13\", \"5\", \"/\", \"+\"] -> (4 + (13 / 5)) -> 6\n Solution: stack.\n */\nclass Solution {\npublic:\n    int evalRPN(vector<string> &tokens) {\n        stack<int> s;\n        for (int i = 0; i < tokens.size(); ++i) {\n            if (tokens[i] != \"+\" && tokens[i] != \"-\" && tokens[i] != \"*\" && tokens[i] != \"/\")\n                s.push(stoi(tokens[i]));\n            else {\n                int op2 = s.top();s.pop();\n                int op1 = s.top();s.pop();\n                int result = 0;\n                if(tokens[i] == \"+\")\n                    result = op1 + op2;\n                else if(tokens[i] == \"-\")\n                    result = op1 - op2;\n                else if(tokens[i] == \"*\")\n                    result = op1 * op2;\n                else if(tokens[i] == \"/\")\n                    result = op1 / op2;\n                s.push(result);\n            }\n        }\n        return s.top();\n    }\n};\n"
  },
  {
    "path": "ExcelSheetColumnNumber.h",
    "content": "/*\n Author:     King, wangjingui@outlook.com\n Date:       Dec 28, 2014\n Problem:    Excel Sheet Column Number\n Difficulty: Medium\n Source:     https://oj.leetcode.com/problems/excel-sheet-column-number/\n Notes:\n Related to question Excel Sheet Column Title\n\n Given a column title as appear in an Excel sheet, return its corresponding column number.\n\n For example:\n\n    A -> 1\n    B -> 2\n    C -> 3\n    ...\n    Z -> 26\n    AA -> 27\n    AB -> 28 \n\n Solution: 1. ...\n*/\nclass Solution {\npublic:\n    int titleToNumber(string s) {\n        int res = 0;\n        if (s.length() == 0) return 0;\n        for (int i = 0; i < s.length(); ++i) {\n            res = res * 26 + s[i] - 'A' + 1;\n        }\n        return res;\n    }\n};"
  },
  {
    "path": "ExcelSheetColumnTitle.h",
    "content": "/*\n Author:     King, wangjingui@outlook.com\n Date:       Dec 19, 2014\n Problem:    Excel Sheet Column Title \n Difficulty: Easy\n Source:     https://oj.leetcode.com/problems/excel-sheet-column-title/\n Notes:\n Given a non-zero positive integer, return its corresponding column title as appear in an Excel sheet.\n\n For example:\n\n    1 -> A\n    2 -> B\n    3 -> C\n    ...\n    26 -> Z\n    27 -> AA\n    28 -> AB \n\n Solution: 1. Iteration.\n           2&3. recursion.\n */\n\nclass Solution {\npublic:\n    string convertToTitle_1(int n) {\n        string res;\n        while (n){\n            res.push_back((n - 1)%26 + 'A');\n            n = (n - 1) / 26;\n        }\n        reverse(res.begin(), res.end());\n        return res;\n    }\n    void convertToTitleRe(int n, string &res) {\n        if (n == 0) return;\n        convertToTitleRe((n-1)/26, res);\n        res.push_back((n-1)%26 + 'A');\n    }\n    string convertToTitle_2(int n) {\n        string res;\n        convertToTitleRe(n, res);\n        return res;\n    }\n    void convertToTitleRe3(int n, string &res) {\n        if (n == 0) return;\n        res.push_back((n-1)%26 + 'A');\n        convertToTitleRe3((n-1)/26, res);\n    }\n    string convertToTitle(int n) {\n        string res;\n        convertToTitleRe3(n, res);\n        reverse(res.begin(), res.end());\n        return res;\n    }\n};"
  },
  {
    "path": "FactorialTrailingZeroes.cpp",
    "content": "/*\n Author:     King, wangjingui@outlook.com\n Date:       Dec 13, 2014\n Problem:    Factorial Trailing Zeroes\n Difficulty: Easy\n Source:     https://oj.leetcode.com/problems/factorial-trailing-zeroes/\n Notes:\n Given an integer n, return the number of trailing zeroes in n!.\n\n Note: Your solution should be in logarithmic time complexity.\n\n Solution: ...\n */\n\nclass Solution {\npublic:\n    int trailingZeroes(int n) {\n        int res = 0;\n        while (n) {\n            res += n / 5;\n            n /= 5;\n        }\n        return res;\n    }\n};"
  },
  {
    "path": "FindMinimumInRotatedSortedArray.h",
    "content": "/*\n Author:     King, higuige@gmail.com\n Date:       Oct 22, 2014\n Problem:    Find Minimum in Rotated Sorted Array\n Difficulty: Medium\n Source:     https://oj.leetcode.com/problems/find-minimum-in-rotated-sorted-array/\n Notes:\n Suppose a sorted array is rotated at some pivot unknown to you beforehand.\n (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).\n\n Find the minimum element.\n\n You may assume no duplicate exists in the array.\n*/\nclass Solution {\npublic:\n    int findMin(vector<int> &num) {\n        if(num.empty()) return 0;\n        int size = num.size();\n        int left = 0;\n        int right = size - 1;\n        while (left < right && num[left] >= num[right]) {\n            int mid = (left + right) / 2;\n            if (num[mid] > num[right]) {\n                left = mid + 1;\n            } else {\n                right = mid;\n            }\n        }\n        return num[left];\n    }\n};\n"
  },
  {
    "path": "FindMinimumInRotatedSortedArrayII.h",
    "content": "/*\n Author:     King, higuige@gmail.com\n Date:       Oct 22, 2014\n Problem:    Find Minimum in Rotated Sorted ArrayII\n Difficulty: Hard\n Source:     https://oj.leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/\n Notes:\n Suppose a sorted array is rotated at some pivot unknown to you beforehand.\n (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).\n\n Find the minimum element.\n\n The array may contain duplicates.\n*/\nclass Solution {\npublic:\n    int findMin(vector<int> &num) {\n        if(num.empty()) return 0;\n        int size = num.size();\n        int left = 0;\n        int right = size - 1;\n        while (left < right && num[left] >= num[right]) {\n            int mid = (left + right) / 2;\n            if (num[mid] > num[right]) {\n                left = mid + 1;\n            } else if (num[mid] < num[left]) {\n                right = mid;\n            } else {\n                ++left;\n            }\n        }\n        return num[left];\n    }\n};"
  },
  {
    "path": "FindPeakElement.h",
    "content": "/*\n Author:     King, wangjingui@outlook.com\n Date:       Dec 06, 2014\n Problem:    Find Peak Element\n Difficulty: Medium\n Source:     https://oj.leetcode.com/problems/find-peak-element/\n Notes:\n A peak element is an element that is greater than its neighbors.\n Given an input array where num[i] ≠ num[i+1], find a peak element and return its index.\n You may imagine that num[-1] = num[n] = -∞.\n For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2.\n\n Find the peak element.\n*/\n\nclass Solution {\npublic:\n    int findPeakElement(const vector<int> &num) {\n        int n = num.size();\n        int left = 0, right = n - 1,mid = -1;\n        while (left <= right) {\n            mid = (left + right) / 2;\n            if ((mid == 0 || num[mid-1] <= num[mid]) && (mid == n -1 || num[mid+1] <= num[mid]))\n                return mid;\n            if (mid > 0 && num[mid - 1] > num[mid]) {\n                right = mid - 1;\n            } else if (num[mid + 1] > num[mid]) {\n                left = mid + 1;\n            }\n        }\n        return mid;\n    }\n};\n"
  },
  {
    "path": "FirstMissingPositive.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 21, 2013\n Problem:    First Missing Positive\n Difficulty: Medium\n Source:     http://leetcode.com/onlinejudge#question_41\n Notes:\n Given an unsorted integer array, find the first missing positive integer.\n For example,\n Given [1,2,0] return 3,\n and [3,4,-1,1] return 2.\n Your algorithm should run in O(n) time and uses constant space.\n\n Solution: Although we can only use constant space, we can still exchange elements within input A!\n           Swap elements in A and try to make all the elements in A satisfy: A[i] == i + 1.\n           Pick out the first one that does not satisfy A[i] == i + 1.\n */\n\nclass Solution {\npublic:\n    int firstMissingPositive(int A[], int n) {\n        int i = 0;\n        while (i < n)\n        {\n            if (A[i] != (i+1) && A[i] >= 1 && A[i] <= n && A[A[i]-1] != A[i])\n                swap(A[i], A[A[i]-1]);\n            else\n                i++;\n        }\n        for (i = 0; i < n; ++i)\n            if (A[i] != (i+1))\n                return i+1;\n        return n+1;\n    }\n};"
  },
  {
    "path": "FlattenBinaryTreetoLinkedList.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com : King, higuige@gmail.com\n Date:       Apr 28, 2013\n Update:     Oct 7, 2014\n Problem:    Flatten Binary Tree to Linked List\n Difficulty: Medium\n Source:     http://leetcode.com/onlinejudge#question_114\n Notes:\n Given a binary tree, flatten it to a linked list in-place.\n For example,\n Given\n     1\n    / \\\n   2   5\n  / \\   \\\n 3   4   6\n The flattened tree should look like:\n 1\n  \\\n   2\n    \\\n     3\n      \\\n       4\n        \\\n         5\n          \\\n           6\n Hints:\n If you notice carefully in the flattened tree, each node's right child points to the next node\n of a pre-order traversal.\n\n Solution: Recursion. Return the last element of the flattened sub-tree.\n */\n\n/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    void flatten(TreeNode *root) {\n        flatten_3(root);\n    }\n\n    void flatten_1(TreeNode *root) {\n        if (root == NULL) return;\n        flatten_1(root->left);\n        flatten_2(root->right);\n        if (root->left == NULL) return;\n        TreeNode *p = root->left;\n        while (p->right) p = p->right;\n        p->right = root->right;\n        root->right = root->left;\n        root->left = NULL;\n    }\n\n    TreeNode * dfs (TreeNode * root, TreeNode * tail){\n        if(root == NULL) return tail;\n        root->right = dfs(root->left,dfs(root->right,tail));\n        root->left = NULL;\n        return root;\n    }\n    void flatten_2(TreeNode *root) {\n        if(root == NULL) return;\n        dfs(root, NULL);\n    }\n    void flatten_3(TreeNode *root) {\n        if(root==nullptr) return;\n        stack<TreeNode*> s;\n        s.push(root);\n        while(!s.empty()){\n            auto p=s.top();\n            s.pop();\n            if(p->right) s.push(p->right);\n            if(p->left) s.push(p->left);\n            p->left = nullptr;\n            if(!s.empty()){\n                p->right=s.top();\n            }else p->right = nullptr;\n        }\n    }\n\n    void flatten_4(TreeNode *root) {\n        TreeNode *end = NULL;\n        flattenRe(root, end);\n    }\n\n    void flattenRe(TreeNode *node, TreeNode *&end) {\n        if (!node) return;\n        TreeNode *lend = NULL, *rend = NULL;\n        flattenRe(node->left, lend);\n        flattenRe(node->right, rend);\n        if (node->left) {\n            lend->right = node->right;\n            node->right = node->left;\n            node->left = NULL;\n        }\n        end = rend ? rend : (lend ? lend : node);\n    }\n};"
  },
  {
    "path": "FractionToRecurringDecimal.h",
    "content": "/*\n Author:     King, wangjingui@outlook.com\n Date:       Dec 15, 2014\n Problem:    Fraction to Recurring Decimal\n Difficulty: Easy\n Source:     https://oj.leetcode.com/problems/fraction-to-recurring-decimal/\n Notes:\n Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.\n\n If the fractional part is repeating, enclose the repeating part in parentheses.\n\n For example,\n\n Given numerator = 1, denominator = 2, return \"0.5\".\n Given numerator = 2, denominator = 1, return \"2\".\n Given numerator = 2, denominator = 3, return \"0.(6)\".\n\n Solution: ...\n */\nclass Solution {\npublic:\n    string fractionToDecimal(int numerator, int denominator) {\n        if (numerator == 0) return string(\"0\");\n        bool flag = (numerator < 0)^(denominator < 0);\n        long long Numerator = abs((long long)numerator);\n        long long Denominator = abs((long long)denominator);\n        string res;\n        if (flag == true) res.push_back('-');\n        ostringstream out;\n        out << (Numerator / Denominator);\n        res.insert(res.size(),out.str());\n        Numerator = Numerator % Denominator;\n        if (Numerator == 0) return res;\n        res.push_back('.');\n        unordered_map<int, int> map;\n        for (int i = res.size(); Numerator != 0; ++i) {\n            if (map.find(Numerator) != map.end()) break;\n            map[Numerator] = i;\n            Numerator *= 10;\n            res.push_back((Numerator / Denominator) + '0');\n            Numerator %= Denominator;\n        }\n        if (Numerator == 0) return res;\n        res.insert(map[Numerator],\"(\");\n        res.push_back(')');\n        return res;\n    }\n};"
  },
  {
    "path": "GasStation.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Oct 3, 2013\n Problem:    Gas Station\n Difficulty: Easy\n Source:     http://oj.leetcode.com/problems/gas-station/\n Notes:\n There are N gas stations along a circular route, where the amount of gas at station i is gas[i].\n You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.\n Return the starting gas station's index if you can travel around the circuit once, otherwise return -1.\n The solution is guaranteed to be unique.\n\n Solution: ...\n*/\n\nclass Solution {\npublic:\n    int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {\n        int N = gas.size();\n        int res = 0, min = gas[0] - cost[0], sum = min;\n        for (int i = 1; i < N; ++i)\n        {\n            sum += gas[i] - cost[i];\n            if (sum < min) {\n                min = sum;\n                res = i;\n            }\n        }\n        return sum >= 0 ? (res + 1) % N : -1;\n    }\n};"
  },
  {
    "path": "GenerateParentheses.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       May 17, 2013\n Update:     Jul 20, 2013\n Problem:    Generate Parentheses\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_22\n Notes:\n Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.\n For example, given n = 3, a solution set is:\n \"((()))\", \"(()())\", \"(())()\", \"()(())\", \"()()()\"\n\n Solution: Place n left '(' and n right ')'.\n           Cannot place ')' if there are no enough matching '('.\n */\n\nclass Solution {\npublic:\n    vector<string> generateParenthesis(int n) {\n        vector<string> res;\n        generateParenthesisRe(res, n, n, \"\");\n        return res;\n    }\n\n    void generateParenthesisRe(vector<string> &res, int left, int right, string s) {\n        if (left == 0 && right == 0)\n            res.push_back(s);\n        if (left > 0)\n            generateParenthesisRe(left - 1, right, s + \"(\");\n        if (right > left)\n            generateParenthesisRe(left, right - 1, s + \")\");\n    }\n};\n"
  },
  {
    "path": "GrayCode.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       May 16, 2013\n Problem:    Gray Code\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_89\n Notes:\n The gray code is a binary numeral system where two successive values differ in only one bit.\n Given a non-negative integer n representing the total number of bits in the code, print the \n sequence of gray code. A gray code sequence must begin with 0.\n For example, given n = 2, return [0,1,3,2]. Its gray code sequence is:\n 00 - 0\n 01 - 1\n 11 - 3\n 10 - 2\n Note:\n For a given n, a gray code sequence is not uniquely defined.\n For example, [0,2,3,1] is also a valid gray code sequence according to the above definition.\n For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that.\n\n Solution: Refer to http://en.wikipedia.org/wiki/Gray_code.\n */\n\nclass Solution {\npublic:\n    vector<int> grayCode(int n) {\n        vector<int> result(1 << n, 0);\n        for (int i = 0; i < 1 << n; ++i)\n            result[i] = (i >> 1) ^ i;\n        return result;\n    }\n};\n"
  },
  {
    "path": "ImplementstrStr().h",
    "content": "/*\n Author:     King, wangjingui@outlook.com\n Date:       Dec 17, 2014\n Problem:    Implement strStr()\n Difficulty: Easy\n Source:     https://oj.leetcode.com/problems/implement-strstr/\n Notes:\n Implement strStr().\n Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.\n\n Solution: 1. Check in the haystack one by one. If not equal to needle, reset the pointer.(TLE)\n           2. Classice KMP solution.\n           3. Simplified RK Soluiton. Thanks for [wenyuanhust, wenyuanhust@gmail.com]\n */\nclass Solution {\npublic:\n    int strStr_1(char *haystack, char *needle) {\n        int sLen = strlen(haystack);\n        const int tLen = strlen(needle);\n        if (tLen == 0) return 0;\n        if(haystack==NULL || needle==NULL || sLen==0) return -1;\n        int i = 0, j =0;\n        while (i < sLen) {\n            j = 0;\n            int k = i;\n            while (j < tLen && haystack[k] == needle[j]) {\n                ++k, ++j;\n            }\n            if (j == tLen) return k - j;\n            ++i;\n        }\n        return -1;\n    }\n    void getNext(char * T, int next[], int n){\n        int i=0, j=-1;\n        next[0]=-1;\n        while(i<n){\n            while(j>-1&&T[j]!=T[i]) j = next[j];\n            i++,j++;\n            if(T[j]==T[i]) next[i]=next[j];\n            else next[i]=j;\n        }\n    }\n    int strStr_2(char *haystack, char *needle) {\n        int sLen = strlen(haystack);\n        const int tLen = strlen(needle);\n        if (tLen == 0) return 0;\n        if(haystack==NULL || needle==NULL || sLen==0) return -1;\n        \n        int next[tLen+1];\n        getNext(needle,next,tLen);\n        \n        int i=0, j=0;\n        while(i<sLen){\n            while(j>-1&&needle[j]!=haystack[i]) j = next[j];\n            i++,j++;\n            if(j==tLen){\n                return i - j;\n            }\n        }\n        return -1;\n    }\n    int strStr_3(char *haystack, char *needle) {\n        if (needle && *needle == '\\0') return 0;\n        if (haystack == NULL || needle == NULL || *haystack == '\\0') return -1;\n        long long fh = 0, fn = 0;\n        char *n = needle, *tail = haystack, *head = haystack;\n        while (*n) {\n            if (*tail == '0') return -1;\n            fh += *tail;\n            fn += *n;\n            ++n, ++tail;\n        }\n        --tail;\n        while (*tail) {\n            if (fn == fh) {\n                char *pTemp = head,*nTemp = needle;\n                while (*nTemp && *nTemp == *pTemp) {\n                    ++nTemp; ++pTemp;\n                }\n                if (*nTemp == '\\0') return head - haystack;\n            }\n            fh -= *head;\n            ++tail;\n            ++head;\n            fh += *tail;\n        }\n        return -1;\n    }\n};"
  },
  {
    "path": "InsertInterval.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com : King, wangjingui@outlook.com\n Date:       Jun 7, 2013\n Update:     Dec 14, 2014\n Problem:    Insert Interval\n Difficulty: Medium\n Source:     https://oj.leetcode.com/problems/insert-interval/\n Notes:\n Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).\n You may assume that the intervals were initially sorted according to their start times.\n Example 1:\n Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].\n Example 2:\n Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16].\n This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].\n\n Solution: For example 2:\n           1. compare [1,2] with [4,9], then insert [1,2];\n           2. merge [3,5] with [4,9], get newInterval = [3,9];\n           3. merge [6,7] with [3,9], get newInterval = [3,9];\n           4. merge [8,10] with [3,9], get newInterval = [3,10];\n           5. compare [12,16] with [3,10], insert newInterval [3,10], then all the remaining intervals...\n           Solution 1 : Time O(N).\n           Solution 2 : Time O(Log(N)).\n*/\n\n/**\n * Definition for an interval.\n * struct Interval {\n *     int start;\n *     int end;\n *     Interval() : start(0), end(0) {}\n *     Interval(int s, int e) : start(s), end(e) {}\n * };\n */\nclass Solution {\npublic:\n    vector<Interval> insert_1(vector<Interval> &intervals, Interval newInterval) {\n        vector<Interval> res;\n        vector<Interval>::iterator it = intervals.begin();\n        bool inserted = false;\n        for (; it != intervals.end(); ++it)\n        {\n            if (inserted == true || it->end < newInterval.start) // non-overlaping\n            {\n                res.push_back(*it);\n            }\n            else if (newInterval.end < it->start)\n            {\n                res.push_back(newInterval);\n                res.push_back(*it);\n                inserted = true;\n            }\n            else\n            {\n                newInterval.start = min(it->start, newInterval.start);\n                newInterval.end = max(it->end, newInterval.end);\n            }\n        }\n        if (inserted == false)\n            res.push_back(newInterval);\n        return res;\n    }\n    vector<Interval> insert_2(vector<Interval> &intervals, Interval newInterval) {\n        vector<Interval> res;\n        int n = intervals.size();\n        int left = 0, right = n-1;\n        while(left<=right){\n            int mid = (left+right)/2;\n            if(intervals[mid].start>newInterval.start) right=mid-1;\n            else left = mid+1;\n        }\n        int idxStart = right;\n        left = 0; right = n-1;\n        while(left<=right){\n            int mid = (left+right)/2;\n            if(intervals[mid].end>=newInterval.end) right = mid -1;\n            else left = mid+1;\n        }\n        int idxEnd = left;\n        \n        if (idxStart>=0 && newInterval.start<=intervals[idxStart].end)\n        {\n            newInterval.start=intervals[idxStart--].start;\n        }\n        \n        if (idxEnd<intervals.size() && newInterval.end>=intervals[idxEnd].start)\n        {\n            newInterval.end=intervals[idxEnd++].end;\n        }\n        for(int i=0;i<=idxStart;i++)\n            res.push_back(intervals[i]);\n        res.push_back(newInterval);\n        for(int i=idxEnd;i<intervals.size();i++)\n            res.push_back(intervals[i]);\n        return res;\n    }\n};"
  },
  {
    "path": "InsertionSortList.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Mar 5, 2014\n Problem:    Insertion Sort List\n Difficulty: Easy\n Source:     http://oj.leetcode.com/problems/insertion-sort-list/\n Notes:\n Sort a linked list using insertion sort.\n\n Solution: ...\n*/\n\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(int x) : val(x), next(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    ListNode *insertionSortList(ListNode *head) {\n        ListNode dummy(INT_MIN); \n        dummy.next = head;\n        ListNode *cur = &dummy;\n        while (cur->next) {\n            if (cur->next->val >= cur->val)\n                cur = cur->next;\n            else\n                insert(&dummy, cur, cur->next);\n        }\n        return dummy.next;\n    }\n    \n    void insert(ListNode *head, ListNode *tail, ListNode *node) {\n        ListNode *cur = head;\n        while (cur->next->val < node->val)\n            cur = cur->next;\n        tail->next = node->next;\n        node->next = cur->next;\n        cur->next = node;\n    }\n};"
  },
  {
    "path": "IntegertoRoman.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       May 13, 2013\n Problem:    Integer to Roman\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_12\n Notes:\n Given an integer, convert it to a roman numeral.\n Input is guaranteed to be within the range from 1 to 3999.\n\n Solution: Buffer the roman numbers.\n */\n\nclass Solution {\npublic:\n    const string rom[4][10] = {{\"\", \"I\", \"II\", \"III\", \"IV\", \"V\", \"VI\", \"VII\", \"VIII\", \"IX\"},\n                               {\"\", \"X\", \"XX\", \"XXX\", \"XL\", \"L\", \"LX\", \"LXX\", \"LXXX\", \"XC\"},\n                               {\"\", \"C\", \"CC\", \"CCC\", \"CD\", \"D\", \"DC\", \"DCC\", \"DCCC\", \"CM\"},\n                               {\"\", \"M\", \"MM\", \"MMM\"}};\n    string intToRoman_1(int num) {\n        string res;\n        int i = 3;\n        while (num > 0)\n        {\n            int divisor = (int)pow(10, i);\n            res += rom[i][num / divisor];\n            num %= divisor;\n            i--;\n        }\n        return res;\n    }\n    string intToRoman_2(int num) {\n        int values[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };\n        string numerals[] = {\"M\", \"CM\", \"D\", \"CD\", \"C\", \"XC\", \"L\", \"XL\", \"X\", \"IX\", \"V\", \"IV\", \"I\" };\n        string res;\n        for (int i = 0; i < 13; ++i) {\n            while (num >= values[i]) {\n                num -= values[i];\n                res += numerals[i];\n            }\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "InterleavingString.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       May 6, 2013\n Problem:    Interleaving String\n Difficulty: Medium\n Source:     http://leetcode.com/onlinejudge#question_97\n Notes:\n Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.\n For example,\n Given:\n s1 = \"aabcc\",\n s2 = \"dbbca\",\n When s3 = \"aadbbcbcac\", return true.\n When s3 = \"aadbbbaccc\", return false.\n\n Solution: 1. dp. O(MN) time & space. 'dp[i][j] == true' means that there is at least one way to construct \n              the string s3[0...i+j-1] by interleaving s1[0...j-1] and s2[0...i-1].\n           2. Recursion. Okay for Small but TLE for Large Test data.\n */\n\nclass Solution {\npublic:\n    bool isInterleave(string s1, string s2, string s3) {\n        return isInterleave_1(s1, s2, s3);\n    }\n\n    bool isInterleave_1(string s1, string s2, string s3) {\n        int M = s1.size(), N = s2.size(), K = s3.size();\n        if (M + N != K) return false;\n        \n        bool dp[N+1][M+1];\n        dp[0][0] = true;\n        for (int i = 1; i <= N; ++i)\n            dp[i][0] = dp[i-1][0] && s2[i-1] == s3[i-1];\n        for (int j = 1; j <= M; ++j)\n            dp[0][j] = dp[0][j-1] && s1[j-1] == s3[j-1];\n\n        for (int i = 1; i <= N; ++i)\n            for (int j = 1; j <= M; ++j)\n                dp[i][j] = dp[i-1][j] && s2[i-1] == s3[i+j-1] ||\n                           dp[i][j-1] && s1[j-1] == s3[i+j-1];\n\n        return dp[N][M];\n    }\n    \n    bool isInterleave_2(string s1, string s2, string s3) {\n        return isInterleaveRe(s1.c_str(), s2.c_str(), s3.c_str());\n    }\n\n    bool isInterleaveRe(const char *s1, const char *s2, const char *s3)\n    {\n        if (*s1 == '\\0' && *s2 == '\\0' && *s3 == '\\0') return true;\n        if (*s3 == '\\0') return false;\n        if (*s1 == '\\0') return strcmp(s2, s3) == 0;\n        if (*s2 == '\\0') return strcmp(s1, s3) == 0;\n\n        return *s1 == *s3 && isInterleaveRe(s1+1, s2, s3+1) || \n               *s2 == *s3 && isInterleaveRe(s1, s2+1, s3+1);\n    }\n};\n"
  },
  {
    "path": "IntersectionOfTwoLinkedLists.h",
    "content": "/*\n Author:     King, wangjingui@outlook.com\n Date:       Nov 28, 2014\n Problem:    Intersection of Two Linked Lists \n Difficulty: Easy\n Source:     https://oj.leetcode.com/problems/intersection-of-two-linked-lists/\n\n Notes:\n Write a program to find the node at which the intersection of two singly linked lists begins.\n Hints:\n    If the two linked lists have no intersection at all, return null.\n    The linked lists must retain their original structure after the function returns.\n    You may assume there are no cycles anywhere in the entire linked structure.\n    Your code should preferably run in O(n) time and use only O(1) memory.\n\n\n Solution: Two iteration.\n*/\n\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(int x) : val(x), next(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {\n        ListNode * cur = NULL;\n        int lenA = 0, lenB = 0;\n        cur = headA;\n        while (cur) {\n            ++lenA;\n            cur = cur->next;\n        }\n        cur = headB;\n        while (cur) {\n            ++lenB;\n            cur = cur->next;\n        }\n        if (lenA >= lenB) {\n            int diff = lenA - lenB;\n            while (diff > 0) {\n                headA = headA->next;\n                --diff;\n            }\n            while (headA && headB) {\n                if(headA == headB) {\n                    return headA;\n                }\n                headA = headA->next;\n                headB = headB->next;\n            }\n        } else {\n            int diff = lenB - lenA;\n            while (diff > 0) {\n                headB = headB->next;\n                --diff;\n            }\n            while (headA && headB) {\n                if(headA == headB) {\n                    return headA;\n                }\n                headA = headA->next;\n                headB = headB->next;\n            }\n        }\n        return NULL;\n    }\n};"
  },
  {
    "path": "JumpGame.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 21, 2013\n Update:     Jul 12, 2013\n Problem:    Jump Game\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_55\n Notes:\n Given an array of non-negative integers, you are initially positioned at the first index of the array.\n Each element in the array represents your maximum jump length at that position.\n Determine if you are able to reach the last index.\n For example:\n A = [2,3,1,1,4], return true.\n A = [3,2,1,0,4], return false.\n\n Solution: Updated solution: try every reachable index. \n           Thank to Wenxin Xing for kindly feedback and pointing out my big mistake:)\n */\n\nclass Solution {\npublic:\n    bool canJump(int A[], int n) {\n        int start = 0, end = 0;\n        while (start <= end && end < n-1)\n        {\n            end = max(end, start + A[start]);\n            start++;\n        }\n        return end >= (n-1);\n    }\n};\n"
  },
  {
    "path": "JumpGameII.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 21, 2013\n Update:     Dec 22, 2014\n Problem:    Jump Game II\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_45\n Notes:\n Given an array of non-negative integers, you are initially positioned at the first index of the array.\n Each element in the array represents your maximum jump length at that position.\n Your goal is to reach the last index in the minimum number of jumps.\n For example:\n Given array A = [2,3,1,1,4]\n The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)\n\n Solution: Jump to the position where we can jump farthest (index + A[index]) next time.\n */\n\nclass Solution {\npublic:\n    int jump_1(int A[], int n) {\n        int start = 0;\n        int res = 0;\n        while (start < n-1)\n        {\n            res++;\n            if (start + A[start] >= n-1)\n                return res;\n            int mx = start;\n            for (int i = start + 1; i <= start + A[start]; ++i)\n                if (i + A[i] >= mx + A[mx])\n                    mx = i;\n            start = mx;\n        }\n    }\n    int jump_2(int A[], int n) {\n        if(n==1) return 0;\n        int res = 0;\n        int last = 0;\n        int cur = 0;\n        for(int i=0;i<n;i++){\n            if(i>last){\n                last = cur;\n                ++res;\n                if (cur >= n - 1) break;\n            }\n            cur = max(cur,i+A[i]);\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "LRUCache.h",
    "content": "/*\n Author:     Matthew Jin, marthew777@gmail.com\n Date:       March 12, 2014\n Problem:    LRU Cache\n Difficulty: Easy\n Source:     http://oj.leetcode.com/problems/lru-cache/\n Notes:\n Design and implement a data structure for Least Recently Used (LRU) cache. \n It should support the following operations: get and set. \n get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.\n set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.\n \n Solution: Hash + list.\n*/\nstruct CacheNode{\n    int key;\n    int value;\n    CacheNode(int k, int v) : key(k), value(v) {}\n};\n\nclass LRUCache{\npublic:\n    LRUCache(int capacity) : size(capacity) {\n    }\n    \n    int get(int key){\n        if (cachemap.find(key) != cachemap.end()) {\n            cachelist.splice(cachelist.begin(), cachelist, cachemap[key]);\n            return cachemap[key]->value;\n        }\n        else {\n            return -1;\n        }\n    }\n    \n    void set(int key, int value) {\n        if (cachemap.find(key) != cachemap.end()) {\n            cachelist.splice(cachelist.begin(), cachelist, cachemap[key]);\n            cachemap[key]->value = value;\n        }\n        else {\n            if (size == cachelist.size()) {\n                cachemap.erase(cachelist.back().key);\n                cachelist.pop_back();\n            }\n            cachelist.push_front(CacheNode(key, value));\n            cachemap[key] = cachelist.begin();\n        }\n    }\nprivate:\n    list<CacheNode> cachelist;\n    unordered_map<int, list<CacheNode>::iterator> cachemap;\n    int size;\n};\n"
  },
  {
    "path": "LargestNumber.h",
    "content": "/*\n Author:     King, nkuwjg@gmail.com\n Date:       Jan 13, 2015\n Problem:    ZigZag Conversion\n Difficulty: Medium\n Source:     https://oj.leetcode.com/problems/largest-number/\n Notes:\n Given a list of non negative integers, arrange them such that they form the largest number.\n\n For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.\n\n Note: The result may be very large, so you need to return a string instead of an integer.\n\n Solution: ...\n */\nclass Solution {\npublic:\n    static string itos(int i) { // convert int to string\n        stringstream s;\n        s << i;\n        return s.str();\n    }\n    static bool cmp(const int & a, const int &b) {\n        string s1 = itos(a), s2 = itos(b);\n        return s1+s2>s2+s1;\n    }\n    string largestNumber(vector<int> &num) {\n        sort(num.begin(),num.end(), cmp);\n        stringstream res;\n        int i = 0;\n        while ((i < num.size() -1) && num[i] == 0) i++;\n        while (i < num.size()) res << num[i++];\n        return res.str();\n    }\n};"
  },
  {
    "path": "LargestRectangleinHistogram.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com : King, higuige@gmail.com\n Date:       Oct 6, 2013\n Update:     Oct 8, 2014\n Problem:    Largest Rectangle in Histogram\n Difficulty: Hard\n Source:     http://leetcode.com/onlinejudge#question_84\n Notes:\n Given n non-negative integers representing the histogram's bar height where the width of each \n bar is 1, find the area of largest rectangle in the histogram.\n For example,\n Given height = [2,1,5,6,2,3],\n return 10.\n\n Solution: 1. Only calucate area when reaching local maximum value.\n           2. Keep a non-descending stack. O(n).\n           3. Keep a non-descending stack. O(n). if the vector height is not allowed to be changed.\n*/\nclass Solution {\npublic:\n    int largestRectangleArea(vector<int> &height) {\n        return largestRectangleArea_1(height);\n    }\n    int largestRectangleArea_1(vector<int> &height) {\n        int res = 0;\n        int N = height.size();\n        for (int i = 0; i < N; ++i) {\n            if (i < N - 1 && height[i] <= height[i + 1]) {\n                continue;\n            }\n            int minHeight = height[i];\n            for (int j = i; j >= 0; --j) {\n                minHeight = min(minHeight, height[j]);\n                res = max(res, (i - j + 1) * minHeight);\n            }\n        }\n        return res;\n    }\n    int largestRectangleArea_2(vector<int> &height) {\n        height.push_back(0);\n        int N = height.size();\n        int res = 0, i = 0;\n        stack<int> s;\n        while (i < N) {\n            if (s.empty() || height[i] >= height[s.top()]) {\n                s.push(i++);\n            } else {\n                int idx = s.top(); s.pop();\n                int width = s.empty() ? i : (i - s.top() - 1);\n                res = max(res, height[idx] * width);\n            }\n        }\n        return res;\n    }\n    \n    int largestRectangleArea_3(vector<int> &height) {\n        int N = height.size();\n        int res = 0, i = 0;\n        stack<int> s;\n        while(i < N) {\n            if(s.empty() || height[s.top()] <= height[i]){\n                s.push(i++);\n            }else{\n                int idx = s.top(); s.pop();\n                int width = s.empty() ? i : (i - s.top() - 1);\n                res = max(res, height[idx] * width);\n            }\n        }\n        while(!s.empty()){\n            int idx = s.top(); s.pop();\n            int width = s.empty() ? i : (i - s.top() - 1);\n            res = max(res, height[idx] * width);\n        }\n        return res;\n    }\n};"
  },
  {
    "path": "LengthofLastWord.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 17, 2013\n Problem:    Length of Last Word\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_58\n Notes:\n Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.\n If the last word does not exist, return 0.\n Note: A word is defined as a character sequence consists of non-space characters only.\n For example, \n Given s = \"Hello World\",\n return 5.\n\n Solution: ...\n */\n\nclass Solution {\npublic:\n    int lengthOfLastWord(const char *s) {\n        int res = 0;\n        int length = strlen(s);\n        for (int i = length - 1; i >= 0; --i)\n            if (s[i] != ' ') res++;\n            else if(res > 0) break;\n        return res;\n    }\n};\n"
  },
  {
    "path": "LetterCombinationsofaPhoneNumber.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       May 12, 2013\n Update:     Dec 02, 2014\n Problem:    Letter Combinations of a Phone Number\n Difficulty: Medium\n Source:     http://leetcode.com/onlinejudge#question_17\n Notes:\n Given a digit string, return all possible letter combinations that the number could represent.\n A mapping of digit to letters (just like on the telephone buttons) is given below.\n Input:Digit string \"23\"\n Output: [\"ad\", \"ae\", \"af\", \"bd\", \"be\", \"bf\", \"cd\", \"ce\", \"cf\"].\n Note:\n Although the above answer is in lexicographical order, your answer could be in any order you want.\n\n Solution: ...\n */\n\nclass Solution {\npublic:\n    vector<string> letterCombinations(string digits) {\n        vector<string> keyboard {\" \",\"\",\"abc\", \"def\", \"ghi\", \"jkl\", \"mno\", \"pqrs\", \"tuv\", \"wxyz\"};\n        vector<string> res;\n        string s;\n        letterCombinationsRe(keyboard,digits,s,res);\n        return res;\n    }\n    void letterCombinationsRe(vector<string> &keyboard, string &digits, string &s, vector<string>&res){\n        if(s.size() == digits.size()){\n            res.push_back(s);\n            return;\n        }\n        string &letters = keyboard[digits[s.size()]-'0'];\n        for(size_t i = 0; i < letters.size(); ++i){\n            s.push_back(letters[i]);\n            letterCombinationsRe(keyboard, digits,s,res);\n            s.pop_back();\n        }\n    }\n};"
  },
  {
    "path": "LinkedListCycle.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com : King, higuige@gmail.com\n Date:       Nov 9, 2013\n Update:     Oct 5, 2014\n Problem:    Linked List Cycle\n Difficulty: Easy\n Source:     http://oj.leetcode.com/problems/linked-list-cycle/\n Notes:\n Given a linked list, determine if it has a cycle in it.\n Follow up:\n Can you solve it without using extra space?\n\n Solution: two pointers.\n*/\n\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(int x) : val(x), next(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    bool hasCycle(ListNode *head) {\n        ListNode *slow = head, *fast = head;\n        while (fast && fast->next) \n        {   \n            fast = fast->next->next;\n            slow = slow->next;\n            if (fast == slow) return true;\n        }\n        return false;\n    }\n};\n"
  },
  {
    "path": "LinkedListCycleII.h",
    "content": "/*\n Author:     Matthew Jin, marthew777@gmail.com\n Date:       Feb 21, 2014\n Problem:    Linked List Cycle II\n Difficulty: Easy\n Source:     http://oj.leetcode.com/problems/linked-list-cycle-ii/\n Notes:\n Given a linked list, return the node where the cycle begins. If there is no cycle, return null.\n Follow up:\n Can you solve it without using extra space?\n\n Solution: From Matthew. Simpler.\n*/\n\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(int x) : val(x), next(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    ListNode *detectCycle(ListNode *head) {\n        if (head == NULL) return NULL;\n        ListNode *slow = head, *fast = head;\n        while (fast && fast->next) {\n            fast = fast->next->next;\n            slow = slow->next;\n            if (fast == slow) break;\n        }\n        \n        if (fast == NULL || fast->next == NULL) return NULL;\n        \n        fast = head;\n        while (fast != slow) {\n            fast = fast->next;\n            slow = slow->next;\n        }\n        \n        return slow;\n    }\n};\n"
  },
  {
    "path": "LongestCommonPrefix.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com : King, wangjingui@outlook.com\n Date:       Apr 16, 2013\n Update:     Dec 20, 2014\n Problem:    Longest Common Prefix\n Difficulty: Easy\n Source:     https://oj.leetcode.com/problems/longest-common-prefix/\n Notes:\n Write a function to find the longest common prefix string amongst an array of strings.\n\n Solution: ...\n */\nclass Solution {\npublic:\n    string longestCommonPrefix(vector<string> &strs) {\n        if(strs.empty()) return \"\";\n        for(int i = 0;i < strs[0].size(); ++i){\n            for(int j = 1;j < strs.size(); ++j){\n                if(strs[j][i] != strs[0][i]) return strs[0].substr(0,i);\n            }\n        }\n        return strs[0];\n    }\n};\n"
  },
  {
    "path": "LongestConsecutiveSequence.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       May 24, 2013\n Update:     Jun 18, 2014\n Problem:    Longest Consecutive Sequence\n Difficulty: Hard\n Source:     https://oj.leetcode.com/problems/longest-consecutive-sequence/\n Notes:\n Given an unsorted array of integers, find the length of the longest consecutive \n elements sequence.\n For example,\n Given [100, 4, 200, 1, 3, 2],\n The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.\n Your algorithm should run in O(n) complexity.\n\n Solution 1: Update solution. This solution is from Peking2 (http://blog.sina.com.cn/s/blog_b9285de20101iqar.html).\n             This solution is much easier to understand.\n Solution 2: by Yao Liu.\n*/\n\nclass Solution {\npublic:\n    int longestConsecutive(vector<int> &num) {\n        return longestConsecutive1(num);\n    }\n    \n    int longestConsecutive1(vector<int> &num) {\n        unordered_set<int> s;\n        int res = 0;\n        for (int i = 0; i < num.size(); ++i)\n            s.insert(num[i]);\n        for (int i = 0; i < num.size() && !s.empty(); ++i)\n        {\n            if (s.find(num[i]) == s.end())\n                continue;\n            int upper = num[i], lower = num[i];\n            while (s.find(upper+1) != s.end())\n                s.erase(++upper);\n            while (s.find(lower-1) != s.end())\n                s.erase(--lower);\n            if (upper != lower)\n                s.erase(num[i]);\n            res = max(res, upper - lower + 1);\n        }\n        return res;\n    }\n    \n    int longestConsecutive2(vector<int> &num) {\n        int longest = 0;\n        unordered_map<int, int> table;\n        for(int i = 0, count = num.size(); i < count; ++i) \n            if(table.find(num[i]) == table.end()) {\n                int val = num[i], update;\n                if(table.find(val - 1) != table.end() && table.find(val + 1) != table.end())\n                    // assigning to table[val] here is only for adding val as a key of the hashtable.\n                    update = table[val] = \n                             table[val - table[val - 1]] = \n                             table[val + table[val + 1]] = \n                             table[val - 1] + table[val + 1] + 1; \n                else if(table.find(val - 1) != table.end())\n                    update = table[val] = ++table[val - table[val - 1]];\n                else if(table.find(val + 1) != table.end())\n                    update = table[val] = ++table[val + table[val + 1]];\n                else \n                    update = table[val] = 1;\n                longest = max(longest, update);\n            }\n        return longest;\n    }\n};\n"
  },
  {
    "path": "LongestPalindromicSubstring.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Jul 13, 2013\n Update:      Nov 17, 2014 : By wangjingui@outlook.com\n Problem:    Longest Palindromic Substring\n Difficulty: Medium\n Source:     http://leetcode.com/onlinejudge#question_5\n Notes:\n Given a string S, find the longest palindromic substring in S. \n You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.\n\n Solution: 1. Time O(n^2), Space O(n^2)\n           2. Time O(n^2), Space O(n)\n           3. Time O(n^2), Space O(1) (actually much more efficient than 1 & 2)\n           4. Time O(n), Space O(n) (Manacher's Algorithm)\n */\n\nclass Solution {\npublic:\n    string longestPalindrome(string s) {\n        return longestPalindrome_4(s);\n    }\n    string longestPalindrome_1(string s) {\n        int N = s.size();\n        bool dp[N][N];\n        pair<int, int> res = make_pair(0, 0); // start pos and length\n        for (int k = 0; k < N; ++k) // length\n        {\n            for (int i = 0; i < N-k; ++i) // start pos\n            {\n                if (k == 0 || k == 1) \n                    dp[i][i+k] = s[i] == s[i+k];\n                else \n                    dp[i][i+k] = (s[i] == s[i+k]) ? dp[i+1][i+k-1] : false;\n                \n                if (dp[i][i+k] && k+1 > res.second)\n                    res = make_pair(i, k+1);\n            }\n        }\n        return s.substr(res.first, res.second);\n    }\n\n    string longestPalindrome_2(string s) {\n        int N = s.size();\n        bool dp[2][N];\n        pair<int, int> res = make_pair(0, 0);\n        int cur = 1, last = 0;\n        for (int i = 0; i < N; ++i)\n        {\n            cur = !cur; last = !last;\n            for (int j = i; j >= 0; --j)\n            {\n                if (j == i || j == i-1)\n                    dp[cur][j] = s[j] == s[i];\n                else\n                    dp[cur][j] = s[j] == s[i] && dp[last][j+1];\n\n                if (dp[cur][j] && i-j+1 > res.second)\n                    res = make_pair(j, i-j+1);\n            }\n        }\n        return s.substr(res.first, res.second);\n    }\n\n    string longestPalindrome_3(string s) {\n        int N = s.size();\n        pair<int, int> res = make_pair(0, 0); // start pos and length\n        for (int i = 0; i < N; ++i) {\n            for (int j = 0; j <= 1; ++j) {\n                bool isP = true;\n                for (int k = 0; i-k >= 0 && i+j+k < N && isP; ++k) {\n                    isP = s[i-k] == s[i+j+k];\n                    if (isP && j+1+k*2 > res.second)\n                        res = make_pair(i-k, j+1+k*2);\n                }\n            }\n        }\n        return s.substr(res.first, res.second);\n    }\n\n    string longestPalindrome_4(string s) {\n        int N = s.size();\n        int dp[2 * N + 1];\n        int id = 0, mx = 0;\n        for (int i = 0; i < 2 * N + 1; ++i)\n        {\n            int j = 2 * id - i;\n            dp[i] = mx > i ? min(dp[j], mx - i) : 1;\n            int left = i - dp[i], right = i + dp[i];\n            for (; left >= 0 && right <= 2 * N; left--, right++)\n            {\n                if (left % 2 == 0 || s[left/2] == s[right/2]) // padding or char\n                    dp[i]++;\n                else\n                    break;\n            }\n            if (i + dp[i] > mx)\n            {\n                id = i;\n                mx = id + dp[id];\n            }\n        }\n\n        int res = 0;\n        for (int i = 1; i < 2 * N + 1; ++i)\n            if (dp[i] > dp[res])\n                res = i;\n\n        return s.substr(res / 2 - (dp[res] - 1) / 2, dp[res] - 1);\n    }\n};\n"
  },
  {
    "path": "LongestSubstringWithoutRepeatingCharacters.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com, King, wangjingui@outlook.com\n Date:       Apr 16, 2013\n Update:     Dec 12, 2014\n Problem:    Longest Substring Without Repeating Characters\n Difficulty: Medium\n Source:     https://oj.leetcode.com/problems/longest-substring-without-repeating-characters/\n Notes:\n Given a string, find the length of the longest substring without repeating characters. \n For example, the longest substring without repeating letters for \"abcabcbb\" is \"abc\", which the length is 3. \n For \"bbbbb\" the longest substring is \"b\", with the length of 1.\n\n Solution: 1. Pay attention when moving the 'start' pointer forward.\n           2. More space, but maybe faster.\n */\n\nclass Solution {\npublic:\n    int lengthOfLongestSubstring_1(string s) {\n        bool exist[256];\n        memset(exist, false, sizeof(exist));\n        int res = 0;\n        int start = 0, end = 0, N = s.size();\n        while (end < N && start + res < N)\n        {\n            if (!exist[s[end]])\n                exist[s[end++]] = true;\n            else\n                exist[s[start++]] = false;\n            res = max(end - start, res);\n        }\n        return res;\n    }\n    int lengthOfLongestSubstring_2(string s) {\n        int len =  s.length();\n        if(len <= 1) return len;\n        vector<int> hash(256,-1);\n        hash[s[0]]=0;\n        int start = 0, cur = 0, res = 1;\n        while(++cur < len){\n            if(hash[s[cur]]>=start){\n                start = hash[s[cur]]+1;\n            }\n            res = max (res, cur - start + 1);\n            hash[s[cur]] = cur;\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "LongestValidParentheses.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com : Andy, nkuwjg@gmail.com\n Date:       May 6, 2013\n Update:     Jan 15, 2015\n Problem:    Longest Valid Parentheses\n Difficulty: Easy\n Source:     https://oj.leetcode.com/problems/longest-valid-parentheses/\n Notes:\n Given a string containing just the characters '(' and ')', find the length of the longest valid \n (well-formed) parentheses substring.\n For \"(()\", the longest valid parentheses substring is \"()\", which has length = 2.\n Another example is \")()())\", where the longest valid parentheses substring is \"()()\", \n which has length = 4.\n\n Solution: O(n).\n */\n\nclass Solution {\npublic:\n    int longestValidParentheses(string s) {\n        return longestValidParentheses_1(s);\n    }\n    \n    // Solution 1, from fuwutu. Smart!\n    // push the length of last valid parentheses into stack.\n    int longestValidParentheses_1(string s) {\n        stack<int> stk;\n        int res = 0, count = 0;\n        for(int i = 0; i < s.size(); ++i) {\n            if (s[i] == '(') {\n                stk.push(count);\n                count = 0;\n            } else if (!stk.empty()) {\n                count += (1 + stk.top());\n                stk.pop();\n                res = max(res, count);\n            } else {\n                count = 0;\n            }\n        }\n        return res * 2;\n    }\n    \n    // Solution 2, By Annie.\n    // Traverse the string twice, taking O(n) time.\n    // First time, mark all the matching parentheses as '*' (push the index of '(' into <stack>).\n    // Second time, count the longest consecutive '*'.\n    int longestValidParentheses_2(string s) {\n        stack<int> stk;\n        for (int i = 0; i < s.size(); ++i) {\n            if (s[i] == '(') {\n                stk.push(i);\n            } else if (!stk.empty()) {\n                s[stk.top()] = '*';\n                s[i] = '*';\n                stk.pop();\n            }\n        }\n        int res = 0, part = 0;\n        for (int i = 0; i < s.size(); ++i) {\n            if (s[i] == '*') {\n                part++;\n            } else {\n                res = max(res, part);\n                part = 0;\n            }\n        }\n        res = max(res, part);\n        return res;\n    }\n    // Dp Solution. By Andy.\n    int longestValidParentheses_3(string s) {\n        int n = s.size();\n        if(s.empty()) return 0;\n        if(n<=1) return 0;\n        int res = 0;\n        vector<int> f(n,0);\n        for(int i=n-2;i>=0;i--){\n            int match = i + f[i+1] + 1;\n            if(match<n&&s[i]=='('&&s[match]==')'){\n                f[i]=f[i+1]+2;\n                if(match+1<n) f[i]+=f[match+1];\n            }\n            res = max(res,f[i]);\n        }\n        return res;\n    }\n    // From Sun Mian.\n    // O(1) Space, and Traverse the string twice, taking O(n) time.\n    int longestValidParentheses_4(string s) {\n        int counter = 0, val = 0, res = 0;\n        for (int i = 0; i < s.length(); ++i) {\n            counter += s[i] == '(' ? 1 : -1;\n            if (counter < 0) {\n                val = counter = 0;\n                continue;\n            }\n            val += s[i] == '(' ? 0 : 2;\n            res = counter == 0 ? max(res, val) : res;\n        }\n        val = counter = 0;\n        for (int i = s.length() - 1; i >= 0; --i) {\n            counter += s[i] == ')' ? 1 : -1;\n            if (counter < 0) {\n                val = counter = 0;\n                continue;\n            }\n            val += s[i] == ')' ? 0 : 2;\n            res = counter == 0 ? max(res, val) : res;\n        }\n        return res;\n    }\n};"
  },
  {
    "path": "MajorityElement.h",
    "content": "/*\n Author:     King, wangjingui@outlook.com\n Date:       Dec 20, 2014\n Problem:    Majority Element\n Difficulty: Easy\n Source:     https://oj.leetcode.com/problems/majority-element/\n Notes:\n Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.\n\n You may assume that the array is non-empty and the majority element always exist in the array.\n\n Solution: 1. Runtime: O(n) — Moore voting algorithm: We maintain a current candidate and a counter initialized to 0. As we iterate the array, we look at the current element x:\n If the counter is 0, we set the current candidate to x and the counter to 1.\n If the counter is not 0, we increment or decrement the counter based on whether x is the current candidate.\n After one pass, the current candidate is the majority element. Runtime complexity = O(n).\n 2. Runtime: O(n) — Bit manipulation: We would need 32 iterations, each calculating the number of 1's for the ith bit of all n numbers. Since a majority must exist, therefore, either count of 1's > count of 0's or vice versa (but can never be equal). The majority number’s ith bit must be the one bit that has the greater count.\n */\n\nclass Solution {\npublic:\n    int majorityElement_1(vector<int> &num) {\n        int n = num.size();\n        if (n == 0) return 0;\n        if (n == 1) return num[0];\n        int res = num[0], cnt = 1;\n        for (int i = 1; i < num.size(); ++i) {\n            if (cnt == 0) {\n                res = num[i];\n                ++cnt;\n                continue;\n            }\n            if (res == num[i]) ++cnt;\n            else --cnt;\n        }\n        return res;\n    }\n    int majorityElement_2(vector<int> &num) {\n        int n = num.size();\n        if (n == 0) return 0;\n        if (n == 1) return num[0];\n        int res = 0;\n        for (int i = 0; i < 32; ++i) {\n            int one = 0, zero = 0;\n            for (int j = 0; j < n; ++j) {\n                if (((num[j]>>i) & 1) == 1) ++one;\n                else ++zero;\n            }\n            if (one > zero) res = res | (1<<i);\n        }\n        return res;\n    }\n};"
  },
  {
    "path": "MaxPointsOnALine.h",
    "content": "/*\n Author:     Matthew Jin, marthew777@gmail.com : King, higuige@gmail.com\n Date:       Dec 03, 2014\n Problem:    Max Points On a Line\n Difficulty: Easy\n Notes:\n Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.\n Solution: 1. hashmap. Time: O(n^2), Space: O(n);\n           2. high precision.\n*/\n\n/**\n * Definition for a point.\n * struct Point {\n *     int x;\n *     int y;\n *     Point() : x(0), y(0) {}\n *     Point(int a, int b) : x(a), y(b) {}\n * };\n */\n\nclass Solution {\npublic:\n    struct pt {\n        int dx, dy;\n        pt(){dx = 0; dy = 0;}\n        pt(int x, int y) {\n            int g = gcd(abs(x), abs(y));\n            if (x==0 && y==0) dx=0,dy=0;\n            else if(x==0) dx=0,dy=1;\n            else if(y==0) dx=1,dy=0;\n            else if(y>0) dx=x/g,dy=y/g;\n            else if(y<0) dx=-x/g,dy=-y/g;\n        }\n        int gcd(int a, int b) {\n            if(b == 0) return a;\n            else return gcd(b, a%b);\n        }\n        bool operator==(const pt &b) const {\n            return dx == b.dx && dy == b.dy;\n        }\n        bool operator<(const pt &b) const {\n            if(dx == b.dx) return dy < b.dy;\n            return dx < b.dx;\n        }\n    };\n\n    int maxPoints_1(vector<Point> &points) {\n        int N = points.size(), res(0);\n        unordered_map<double, int> m;\n        for (int i =0; i < N; ++i) {\n            m.clear();\n            int ss(1), sp(0);// ss: points with same slope, sp: same points.\n            for (int j = i + 1; j < N; ++j) {\n                double slope = std::numeric_limits<double>::infinity();\n                if (points[i].x != points[j].x) {\n                    slope = 1.0*(points[i].y-points[j].y)/(points[i].x-points[j].x);\n                } else if (points[i].y == points[j].y) {\n                    ++sp; continue;\n                }\n                int tmp = 0;\n                if(m.find(slope) != m.end()) tmp = ++m[slope];\n                else tmp = m[slope] = 2;\n                ss = max(ss, tmp);\n            }\n            res = max(res, ss + sp);\n        }\n        return res;\n    }\n\n    int maxPoints_2(vector<Point> &points) {\n        int N = points.size(), res(0);\n        pt zero(0,0);\n        map<pt, int> m;\n        for (int i=0; i < N; ++i) {\n            m.clear();\n            int ss(0), sp(0);\n            for (int j = 0; j < N; ++j) {\n                pt slope(points[i].x-points[j].x, points[i].y-points[j].y);\n                if (slope == zero) ++sp;\n                else {\n                    ss = max(ss, ++m[slope]);\n                }\n            }\n            res = max(res, ss + sp);\n        }\n        return res;\n    }\n};"
  },
  {
    "path": "MaximalRectangle.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com : King, higuige@gmail.com\n Date:       May 23, 2013\n Update:     Oct 09, 2014\n Problem:    Maximal Rectangle\n Difficulty: Medium\n Source:     http://leetcode.com/onlinejudge#question_85\n Notes:\n Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.\n\n Solution: 1. dp. (72 milli secs for the large).\n              a) dp[i][j] records the number of consecutive '1' on the left and up of the element matrix[i][j].\n              b) For each element(i,j), calculate the area of rectangle including the element itself.\n           2. calculate 'Largest Rectangle in Histogram' for each row.\n           3. Time : O(n ^ 2), Space : O(n).\n */\n\nclass Solution {\npublic:\n    int maximalRectangle(vector<vector<char>> &matrix) {\n        return maximalRectangle_3(matrix);\n    }\n    \n    int maximalRectangle_1(vector<vector<char>> &matrix) {\n        if (matrix.empty() || matrix[0].empty()) return 0;\n        int N = matrix.size(), M = matrix[0].size();\n        pair<int, int> dp[N][M];\n        memset(dp, 0, sizeof(dp));\n        int res = 0;\n        for (int i = 0; i < N; ++i)\n        {\n            for (int j = 0; j < M; ++j)\n            {\n                if (matrix[i][j] == '0')\n                    continue;\n                \n                int x = (j == 0) ? 1 : dp[i][j-1].first + 1;\n                int y = (i == 0) ? 1 : dp[i-1][j].second + 1;\n                dp[i][j] = make_pair(x, y);\n                \n                int minHeight = y;\n                for (int k = j; k > j - x; --k)\n                {\n                    minHeight = min(minHeight, dp[i][k].second);\n                    res = max(res, minHeight * (j - k + 1));\n                }\n            }\n        }\n        return res;\n    }\n    \n    int maximalRectangle_2(vector<vector<char> > &matrix) {\n        if (matrix.empty() || matrix[0].empty()) return 0;\n        int N = matrix.size(), M = matrix[0].size();\n        vector<int> height(M+1, 0);\n        int res = 0;\n        for (int i = 0; i < N; ++i)\n        {\n            for (int j = 0; j < M; ++j)\n                height[j] = (matrix[i][j] == '0') ? 0 : height[j] + 1;\n            res = max(res, largestRectangleArea(height));\n        }\n        return res;\n    }\n    \n    // a little different from 'Largest Rectangle in Histogram'\n    // final 0 is already provided beforehand\n    int largestRectangleArea(const vector<int> &height) {\n        stack<int> stk;\n        int res = 0, N = height.size();\n        for (int i = 0; i < N; ++i)\n        {\n            int count = 0;\n            while (!stk.empty() && stk.top() > height[i])\n            {\n                count++;\n                res = max(res, count * stk.top());\n                stk.pop();\n            }\n            while (count--)\n                stk.push(height[i]);\n\n            stk.push(height[i]);\n        }\n        return res;\n    }\n\n    int maximalRectangle_3(vector<vector<char> > &matrix) {\n        if (matrix.empty()) return 0;\n        int m = matrix.size();\n        int n = matrix[0].size();\n        std::vector<int> H(n, 0);\n        std::vector<int> L(n, 0);\n        std::vector<int> R(n, n);\n        int res = 0;\n        for (int i = 0; i < m; ++i) {\n            int left = 0, right = n;\n            for (int j = 0; j < n; ++j) {\n                if (matrix[i][j] == '1') {\n                    ++H[j];\n                    L[j] = max(left, L[j]);\n                } else {\n                    left = j + 1;\n                    H[j] = 0; L[j] = 0; R[j] = n;\n                }\n            }\n            for (int j = n - 1; j >= 0; --j) {\n                if (matrix[i][j] == '1') {\n                    R[j] = min(R[j], right);\n                    res =  max(res, (R[j] - L[j]) * H[j]);\n                } else {\n                    right = j;\n                }\n            }\n        }\n        return res;\n    }\n\n};\n"
  },
  {
    "path": "MaximumDepthofBinaryTree.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 9, 2013\n Problem:    Maximum Depth of Binary Tree\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_104\n Notes:\n Given a binary tree, find its maximum depth.\n The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.\n\n Solution: Recursion.\n */\n\n/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    int maxDepth(TreeNode *root) {\n        if (!root) return 0;\n        return 1 + max(maxDepth(root->left), maxDepth(root->right));\n    }\n};\n"
  },
  {
    "path": "MaximumGap.h",
    "content": "/*\n Author:     King, wangjingui@outlook.com\n Date:       Dec 14, 2014 \n Problem:    Maximum Gap\n Difficulty: Hard\n Source:     https://oj.leetcode.com/problems/maximum-gap/\n Notes:\n Given an unsorted array, find the maximum difference between the successive elements in its sorted form.\n\n Try to solve it in linear time/space.\n\n Return 0 if the array contains less than 2 elements.\n\n You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range.\n\n Solution: 1. Time : O(nlogn). Space : O(1); \n              Sort the unsorted array, and find the maximum difference.\n           2. Time : O(n). Space : O(n).\n              Drawer Theory. If we put n numbers into (n+1) drawers, \n              then there must be at least one empty drawer. \n              So we can find the maximum difference between two succesive non-empty drawers.\n */\n\nclass Solution {\npublic:\n    int maximumGap_1(vector<int> &num) {\n        sort(num.begin(), num.end());\n        int res = 0;\n        for (int i = 1; i < num.size(); ++i) {\n            res = max(res, num[i] - num[i-1]);\n        }\n        return res;\n    }\n    int maximumGap_2(vector<int> &num) {\n        int n = num.size();\n        if (n < 2) return 0;\n        int minVal = num[0], maxVal = num[0];\n        for (int i = 1; i < n; ++i) {\n            minVal = min(minVal, num[i]);\n            maxVal = max(maxVal, num[i]);\n        }\n        //delta = (maxVal + 1 - minVal) / (n + 1)\n        //idx = (val - minVal) / delta = (val - minVal) * (n + 1) / (maxVal + 1 - minVal)\n        vector<pair<int,int> > pool(n+2,make_pair(-1,-1));\n        for (int i = 0; i < n; ++i) {\n            int idx = (long long)(num[i] - minVal)* (n + 1) / (maxVal + 1 - minVal);\n            if (pool[idx].first == -1) {\n                pool[idx] = make_pair(num[i],num[i]);\n            } else {\n                pool[idx].first = min(pool[idx].first, num[i]);\n                pool[idx].second = max(pool[idx].second, num[i]);\n            }\n        }\n        int last = pool[0].second;\n        int res = 0;\n        for (int i = 1; i < n + 2; ++i) {\n            if (pool[i].first != -1) {\n                res = max(res, pool[i].first - last);\n                last = pool[i].second;\n            }\n        }\n        return res;\n    }\n};"
  },
  {
    "path": "MaximumProductSubarray.h",
    "content": "/*\n Author:     King, higuige@gmail.com\n Date:       Sep 24, 2014\n Update:     Oct 06, 2014\n Problem:    Maximum Product Subarray\n Difficulty: Medium\n Source:     https://oj.leetcode.com/problems/maximum-product-subarray/\n Notes:\n Find the contiguous subarray within an array (containing at least one number) which has the largest product.\n\n For example, given the array [2,3,-2,4],\n the contiguous subarray [2,3] has the largest product = 6.\n*/\nclass Solution {\npublic:\n    int maxProduct(int A[], int n) {\n        if (n <= 0) {\n            return 0;\n        }\n        int maxVal = A[0], minVal = A[0], res = A[0];\n        for (int i = 1; i < n; ++i) {\n            int tmpVal = maxVal;\n            maxVal = max(max(maxVal * A[i], minVal * A[i]), A[i]);\n            minVal = min(min(tmpVal * A[i], minVal * A[i]), A[i]);\n            res = max(res, maxVal);\n        }\n        return res;\n    }\n\n    int maxProduct_2(int A[], int n) {\n        if(n==0) return 0;\n        if(n==1) return A[0];\n        int minVal = 0;\n        int product = 1;\n        int res = A[0];\n        for(int i=0;i<n;i++){\n            product = product*A[i];\n            if(product<0){\n                if(minVal==0) minVal=product;\n                else {\n                    res = max(res,product/minVal);\n                    minVal=max(minVal,product);\n                }\n            }else if(product==0){\n                res = max(res,product);\n                product = 1;\n                minVal=0;\n            }else{\n                res = max(res,product);\n            }\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "MaximumSubarray.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 21, 2013\n Problem:    Maximum Subarray\n Difficulty: Medium\n Source:     http://leetcode.com/onlinejudge#question_53\n Notes:\n Find the contiguous subarray within an array (containing at least one number) which has the largest sum.\n For example, given the array [-2,1,-3,4,-1,2,1,-5,4], the contiguous subarray [4,-1,2,1] has the largest sum = 6.\n\n Solution: dp.\n */\n\nclass Solution {\npublic:\n    int maxSubArray(int A[], int n) {\n        int res = A[0];\n        int dp = A[0];\n        for (int i = 1; i < n; ++i) {\n            dp = max(A[i], dp + A[i]);\n            res = max(dp, res);\n        }\n        return res;\n    }\n};"
  },
  {
    "path": "MedianofTwoSortedArrays.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Jul 10, 2013\n Problem:    Median of Two Sorted Arrays\n Difficulty: Hard\n Source:     http://leetcode.com/onlinejudge#question_4\n Notes:\n There are two sorted arrays A and B of size m and n respectively. \n Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).\n\n Solution: 1. O(m+n)\n           2. O(log(m+n))\n           3. O(logm + logn)\n*/\n\nclass Solution {\npublic:\n    double findMedianSortedArrays(int A[], int m, int B[], int n) {\n        return findMedianSortedArrays_1(A, m, B, n);\n    }\n\n    double findMedianSortedArrays_1(int A[], int m, int B[], int n) {\n        int i = 0, j = 0;\n        int m1 = 0, m2 = 0;\n        int total = m + n;\n\n        for (int k = 0; k <= total / 2; ++k)\n        {\n            int a = (i == m) ? INT_MAX : A[i];\n            int b = (j == n) ? INT_MAX : B[j];\n\n            m1 = m2;\n            m2 = min(a, b);\n\n            if (a < b) i++;\n            else j++;\n        }\n\n        if (total & 0x1) return m2;\n        else return (m1 + m2) / 2.0;\n    }\n\n    double findMedianSortedArrays_2(int A[], int m, int B[], int n) {\n        int total = m + n;\n        if (total & 0x1)\n            return findKthSortedArrays(A, m, B, n, total / 2 + 1);\n        else\n            return (findKthSortedArrays(A, m, B, n, total / 2) + findKthSortedArrays(A, m, B, n, total / 2 + 1)) / 2;\n    }\n\n    double findKthSortedArrays(int A[], int m, int B[], int n, int k) {\n        if (m > n)\n            return findKthSortedArrays(B, n, A, m, k);\n        if (m == 0) return B[k-1];\n        if (k == 1) return min(A[0], B[0]);\n\n        int i = min(k / 2, m);\n        int j = k - i;\n        int a = A[i-1];\n        int b = B[j-1];\n\n        if (a < b) return findKthSortedArrays(A + i, m - i, B, n, k - i);\n        else if (a > b) return findKthSortedArrays(A, m, B + j, n - j, k - j);\n        else return a;\n    }\n\n    double findMedianSortedArrays_3(int A[], int m, int B[], int n) {\n        return findMedian(A, m, B, n, max(0, (m + n) / 2 - n), min(m - 1, (m + n) / 2));\n    }\n\n    double findMedian(int A[], int m, int B[], int n, int l, int r) {\n        if (l > r)\n            return findMedian(B, n, A, m, max(0, (m + n) / 2 - m), min(n, (m + n) / 2));\n\n        int i = (l + r) / 2;\n        int j = (m + n) / 2 - i;\n\n        int Ai_1 = (i == 0) ? INT_MIN : A[i-1];\n        int Bj_1 = (j == 0) ? INT_MIN : B[j-1];\n        int Ai = (i == m) ? INT_MAX : A[i];\n        int Bj = (j == n) ? INT_MAX : B[j];\n\n        if (Ai < Bj_1) return findMedian(A, m, B, n, i+1, r);\n        if (Ai > Bj) return findMedian(A, m, B, n, l, i-1);\n\n        if ((m + n) % 2 == 1) return Ai;\n        else return (Ai + max(Ai_1, Bj_1)) / 2.0;\n    }\n};\n"
  },
  {
    "path": "MergeIntervals.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Jun 7, 2013\n Update:     Jul 15, 2013\n Problem:    Merge Intervals\n Difficulty: Medium\n Source:     http://leetcode.com/onlinejudge#question_56\n Notes:\n Given a collection of intervals, merge all overlapping intervals.\n For example,\n Given [1,3],[2,6],[8,10],[15,18],\n return [1,6],[8,10],[15,18].\n\n Solution: 1. Sort in ascending order of 'start'.\n           2. Traverse the 'intervals', merge or push...\n*/\n\n/**\n * Definition for an interval.\n * struct Interval {\n *     int start;\n *     int end;\n *     Interval() : start(0), end(0) {}\n *     Interval(int s, int e) : start(s), end(e) {}\n * };\n */\nbool compare(Interval a, Interval b)\n{\n    return a.start < b.start;\n}\n\nclass Solution {\npublic:\n    vector<Interval> merge(vector<Interval> &intervals) {\n        int N = intervals.size();\n        if (N <= 1) return intervals;\n        sort(intervals.begin(), intervals.end(), mycompare);\n        vector<Interval> res;\n        Interval last = intervals[0];\n        for (int i = 1; i < N; ++i) \n        {\n            if (intervals[i].start > last.end) {\n                res.push_back(last);\n                last = intervals[i];\n            } else {\n                last.end = max(last.end, intervals[i].end);\n            }\n        }\n        res.push_back(last);\n        return res;\n    }\n};"
  },
  {
    "path": "MergeSortedArray.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 10, 2013\n Update:     Aug 7, 2013\n Problem:    Merge Sorted Array\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_88\n Notes:\n Given two sorted integer arrays A and B, merge B into A as one sorted array.\n Note:\n You may assume that A has enough space to hold additional elements from B. \n The number of elements initialized in A and B are m and n respectively.\n\n Solution: From back to forth.\n */\n\nclass Solution {\npublic:\n    void merge(int A[], int m, int B[], int n) {\n        int i = m - 1;\n        int j = n - 1;\n        int x = m + n - 1;\n        while (i >= 0 && j >= 0)\n            if (A[i] >= B[j]) A[x--] = A[i--];\n            else A[x--] = B[j--];\n        while (j >= 0) A[x--] = B[j--];\n    }\n};\n"
  },
  {
    "path": "MergeTwoSortedLists.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 17, 2013\n Update:     Sep 2, 2013\n Problem:    Merge Two Sorted Lists\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_21\n Notes:\n Merge two sorted linked lists and return it as a new list. \n The new list should be made by splicing together the nodes of the first two lists.\n\n Solution: ...\n */\n\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(int x) : val(x), next(NULL) {}\n * };\n */\n\nclass Solution {\npublic:\n    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {\n        ListNode head(0), *cur = &head;\n        while (l1 && l2) \n        {\n            ListNode **min = l1->val < l2->val ? &l1 : &l2;\n            cur->next = *min;\n            cur = cur->next;\n            *min = (*min)->next;\n        }\n        if (l1) cur->next = l1;\n        if (l2) cur->next = l2;\n        return head.next;\n    }\n};\n"
  },
  {
    "path": "MergekSortedLists.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com : King, wangjingui@outlook.com\n Date:       Apr 6, 2013\n Update:     Nov 17, 2014\n Problem:    Merge k Sorted Lists\n Difficulty: easy\n Source:     http://leetcode.com/onlinejudge#question_23\n Notes:\n Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.\n \n Solution: Find the smallest list-head first using minimum-heap(lgk).\n           complexity: O(N*KlgK)\n */\n\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(int x) : val(x), next(NULL) {}\n * };\n */\n\nclass Mycompare {\npublic:\n    bool operator()(ListNode *a, ListNode *b) {\n        return a->val > b->val;\n    }\n};\n\nclass Solution {\npublic:\n    ListNode *mergeKLists(vector<ListNode *> &lists) {\n        priority_queue<ListNode *, vector<ListNode *>, Mycompare> q;\n        for (int i = 0; i < lists.size(); ++i)\n            if (lists[i])\n                q.push(lists[i]);\n        \n        ListNode dummy(0), *cur = &dummy;\n        while (!q.empty()) {\n            ListNode *node = q.top();\n            q.pop();\n            cur = cur->next = node;\n            if (node->next)\n                q.push(node->next);\n        }\n        return dummy.next;\n    }\n\n    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {\n        ListNode head(0), *cur = &head;\n        while (l1 && l2) \n        {\n            ListNode **min = l1->val < l2->val ? &l1 : &l2;\n            cur->next = *min;\n            cur = cur->next;\n            *min = (*min)->next;\n        }\n        if (l1) cur->next = l1;\n        if (l2) cur->next = l2;\n        return head.next;\n    }\n    \n    ListNode *mergeKLists_2(vector<ListNode *> &lists) {\n        if(lists.size()==0) return NULL;\n        int sz = lists.size();\n        int end = sz - 1;\n        while (end > 0) {\n            int begin = 0;\n            while (begin < end) {\n                lists[begin] = mergeTwoLists(lists[begin], lists[end]);\n                ++begin;\n                --end;\n            }\n        }\n        return lists[0];\n    }\n};\n"
  },
  {
    "path": "MinStack.h",
    "content": "/*\n Author:     King, higuige@gmail.com\n Date:       Nov 14, 2014\n Problem:    Min Stack \n Difficulty: Easy\n Source:     https://oj.leetcode.com/problems/min-stack/\n Notes:\n Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.\n    push(x) -- Push element x onto stack.\n    pop() -- Removes the element on top of the stack.\n    top() -- Get the top element.\n    getMin() -- Retrieve the minimum element in the stack.\n*/\n\nclass MinStack {\npublic:\n    void push(int x) {\n        elements.push(x);\n        if (minstk.empty() || x <= minstk.top()) {\n            minstk.push(x);\n        }\n    }\n\n    void pop() {\n        if (elements.empty()) { \n            return;\n        }\n        if (elements.top() == minstk.top()) {\n            minstk.pop();\n        }\n        elements.pop();\n    }\n\n    int top() {\n        return elements.top();\n    }\n\n    int getMin() {\n        return minstk.top();\n    }\nprivate:\n    stack<int> elements;\n    stack<int> minstk;\n};\n"
  },
  {
    "path": "MinimumDepthofBinaryTree.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 6, 2013\n Update:     Nov 17, 2014 : by King, wangjingui@outlook.com\n Problem:    Minimum Depth of Binary Tree\n Difficulty: easy\n Source:     http://leetcode.com/onlinejudge#question_111\n Notes:\n Given a binary tree, find its minimum depth.\n The minimum depth is the number of nodes along the shortest path from the root node \n down to the nearest leaf node.\n \n Solution: 1. Recursion. Pay attention to cases when the non-leaf node has only one child.\n           2. Iteration + Queue. Contributed by SUN Mian(孙冕).\n */\n\n/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    int minDepth(TreeNode *root) {\n        return minDepth_1(root);\n    }\n    \n    int minDepth_1(TreeNode *root) {\n        if (!root)\n            return 0;\n        \n        if (!root->left)\n            return 1 + minDepth_1(root->right);\n        if (!root->right)\n            return 1 + minDepth_1(root->left);\n        return 1 + min(minDepth_1(root->left), minDepth_1(root->right));\n    }\n    \n    int minDepth_2(TreeNode *root) {\n        if (!root) return 0;\n        queue<TreeNode *> q;\n        q.push(root);\n        TreeNode * rightmost = root;\n        int depth = 1;\n        while (!q.empty())\n        {\n            TreeNode *node = q.front();\n            q.pop();\n            if (!node->left && !node->right) return depth;\n            if (node->left) q.push(node->left);\n            if (node->right) q.push(node->right);\n            if (node == rightmost) {\n                ++depth;\n                rightmost = node->right?node->right:node->left;\n            }\n        }\n    }\n};\n"
  },
  {
    "path": "MinimumPathSum.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 17, 2013\n Update:     Jul 30, 2013\n Problem:    Minimum Path Sum\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_64\n Notes:\n Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right \n which minimizes the sum of all numbers along its path.\n Note: You can only move either down or right at any point in time.\n\n Solution: Dynamic Programming. Space O(N).\n */\n\nclass Solution {\npublic:\n    int minPathSum(vector<vector<int> > &grid) {\n        if (grid.empty()) return INT_MIN;\n        int M = grid.size(), N = grid[0].size();\n        int dp[N];\n        dp[0] = grid[0][0];\n        for (int i = 1; i < N; ++i)\n            dp[i] = grid[0][i] + dp[i-1];\n        \n        for (int i = 1; i < M; ++i)\n        {\n            dp[0] += grid[i][0];\n            for (int j = 1; j < N; ++j)\n                dp[j] = min(dp[j-1], dp[j]) + grid[i][j];\n        }\n        \n        return dp[N-1];\n    }\n};\n"
  },
  {
    "path": "MinimumWindowSubstring.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       May 24, 2013\n Update:     Jul 30, 2013\n Problem:    Minimum Window Substring\n Difficulty: Medium\n Source:     http://leetcode.com/onlinejudge#question_76\n Notes:\n Given a string S and a string T, find the minimum window in S which will contain all the \n characters in T in complexity O(n).\n For example,\n S = \"ADOBECODEBANC\"\n T = \"ABC\"\n Minimum window is \"BANC\".\n Note:\n If there is no such window in S that covers all characters in T, return the empty string \"\".\n If there are multiple such windows, you are guaranteed that there will always be only one unique \n minimum window in S.\n\n Solution: 1. Use two pointers: start and end. \n              First, move 'end'. After finding all the needed characters, move 'start'.\n           2. Use array as hashtable.\n */\n\nclass Solution {\npublic:\n    string minWindow(string S, string T) {\n        int N = S.size(), M = T.size();\n        if (N < M) return \"\";\n        int need[256] = {0};\n        int find[256] = {0};\n        for (int i = 0; i < M; ++i)\n            need[T[i]]++;\n\n        int count = 0, resStart = -1, resEnd = N;\n        for (int start = 0, end = 0; end < N; ++end)\n        {\n            if (need[S[end]] == 0)\n                continue;\n            if (find[S[end]] < need[S[end]])\n                count++;\n            find[S[end]]++;\n            if (count != M) continue;\n            // move 'start'\n            for (; start < end; ++start) {\n                if (need[S[start]] == 0) continue;\n                if (find[S[start]] <= need[S[start]]) break;\n                find[S[start]]--;\n            }\n            // update result\n            if (end - start < resEnd - resStart) {\n                resStart = start;\n                resEnd = end;\n            }\n        }\n        return (resStart == -1) ? \"\" : S.substr(resStart, resEnd - resStart + 1);\n    }\n};"
  },
  {
    "path": "MultiplyStrings.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 23, 2013\n Update:     Aug 20, 2013\n Problem:    Multiply Strings\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_43\n Notes:\n Given two numbers represented as strings, return multiplication of the numbers as a string.\n Note: The numbers can be arbitrarily large and are non-negative.\n\n Solution: Just like what we do when multiplying integers.\n */\n\nclass Solution {\npublic:\n    string multiply(string num1, string num2) {\n        int N = num1.size(), M = num2.size();\n        string res(N+M, '0');\n        for (int i = N - 1; i >= 0; --i)\n        {\n            int carry = 0;\n            for (int j = M - 1; j >= 0; --j)\n            {\n                int sum = carry + (res[i+j+1] - '0') + \n                          (num1[i] - '0') * (num2[j] - '0');\n                res[i+j+1] = sum % 10 + '0';\n                carry = sum / 10;\n            }\n            res[i] += carry;\n        }\n        while (res.size() > 1 && res[0] == '0')\n            res.erase(res.begin());\n        return res;\n    }\n};\n"
  },
  {
    "path": "N-Queens.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 24, 2013\n Update:     Jul 25, 2013\n Problem:    N-Queens\n Difficulty: Medium\n Source:     http://leetcode.com/onlinejudge#question_51\n Notes:\n The n-queens puzzle is the problem of placing n queens on an n*n chessboard such that no two queens attack each other.\n Given an integer n, return all distinct solutions to the n-queens puzzle.\n Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.\n For example,\n There exist two distinct solutions to the 4-queens puzzle:\n [\n [\".Q..\",  // Solution 1\n \"...Q\",\n \"Q...\",\n \"..Q.\"],\n\n [\"..Q.\",  // Solution 2\n \"Q...\",\n \"...Q\",\n \".Q..\"]\n ]\n\n Solution: Recursion (DFS). Use bit-manipulation solution (See N-QueensII for more details).\n */\n\nclass Solution {\npublic:\n    vector<vector<string> > solveNQueens(int n) {\n        vector<vector<string> > res;\n        vector<string> sol;\n        solveNQueensRe(n, 0, 0, 0, sol, res);\n        return res;\n    }\n    \n    void solveNQueensRe(int n, int row, int ld, int rd, vector<string> &sol, vector<vector<string>> &res)\n    {\n        if (row == (1 << n) - 1)\n        {\n            res.push_back(sol);\n            return;\n        }\n        int avail = ~(row | ld | rd);\n        for (int i = n-1; i >= 0; --i)\n        {\n            int pos = 1 << i;\n            if (avail & pos)\n            {\n                string s(n, '.');\n                s[i] = 'Q';\n                sol.push_back(s);\n                solveNQueensRe(n, row | pos, (ld|pos) << 1, (rd|pos) >> 1, sol, res);\n                sol.pop_back();\n            }\n        }\n    }\n};\n"
  },
  {
    "path": "N-QueensII.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 24, 2013\n Update:     Aug 23, 2013\n Problem:    N-Queens II\n Difficulty: Medium\n Source:     http://leetcode.com/onlinejudge#question_52\n Notes:\n The n-queens puzzle is the problem of placing n queens on an n*n chessboard such that no two queens attack each other.\n Given an integer n, return all distinct solutions to the n-queens puzzle.\n Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.\n For example,\n There exist two distinct solutions to the 4-queens puzzle:\n [\n [\".Q..\",  // Solution 1\n \"...Q\",\n \"Q...\",\n \"..Q.\"],\n\n [\"..Q.\",  // Solution 2\n \"Q...\",\n \"...Q\",\n \".Q..\"]\n ]\n\n Solution: 1. Recursion.\n           2. Recursion + bit version. (fast)\n              The idea is from http://www.matrix67.com/blog/archives/266 (in chinese).\n           3. Iteration.\n*/\n\nclass Solution {\npublic:\n    int totalNQueens(int n) {\n        return totalNQueens_2(n);\n    }\n    \n    // solution 1: recursion\n    int totalNQueens_1(int n) \n    {\n        int board[n];\n        memset(board, -1, sizeof(board));\n        int res = 0;\n        totalNQueensRe(n, 0, board, res);\n        return res;\n    }\n    \n    void totalNQueensRe(int n, int row, int board[], int &res)\n    {\n        if (row  == n)\n        {\n            res++;\n            return;\n        }\n        for (int i = 0; i < n; ++i)\n        {\n            if (isValid(board, row, i))\n            {\n                board[row] = i;\n                totalNQueensRe(n, row + 1, board, res);\n                board[row] = -1;\n            }\n        }\n    }\n    \n    bool isValid(int board[], int row, int col)\n    {\n        for (int i = 0; i < row; ++i)\n            if (board[i] == col || row - i == abs(col - board[i]))\n                return false;\n        return true;\n    }\n    \n    // solution 2: bit version\n    int totalNQueens_2(int n) {\n        int res = 0;\n        totalNQueensRe_2(n, 0, 0, 0, res);\n        return res;\n    }\n\n    void totalNQueensRe_2(int n, int row, int ld, int rd, int &res)\n    {\n        if (row == (1 << n) - 1)\n        {\n            res++;\n            return;\n        }\n        int avail = ~(row | ld | rd);\n        for (int i = n - 1; i >= 0; --i)\n        {\n            int pos = 1 << i;\n            if (avail & pos)\n                totalNQueensRe_2(n, row | pos, (ld | pos) << 1, (rd | pos) >> 1, res);\n        }\n    }\n    \n    // solution 3: iterative solution\n    int totalNQueens_3(int n) \n    {\n        int board[n];\n        memset(board, -1, sizeof(board));\n        int row = 0;\n        int res = 0;\n        while (row != -1)\n        {\n            if (row == n)\n            {\n                res++;\n                row--;\n            }\n            int i = board[row] == -1 ? 0 : board[row] + 1;\n            for (; i < n; ++i)\n            {\n                if (isValid(board, row, i))\n                {\n                    board[row] = i;\n                    row++;\n                    break;\n                }\n            }\n            if (i == n)\n            {\n                board[row] = -1;\n                row--;\n            }\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "NextPermutation.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com : King, wangjingui@outlook.com\n Date:       May 6, 2013\n Update:     Dec 16, 2014\n Problem:    Next Permutation\n Difficulty: Medium\n Source:     http://leetcode.com/onlinejudge#question_31\n Notes:\n Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.\n If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).\n The replacement must be in-place, do not allocate extra memory.\n Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.\n 1,2,3 -> 1,3,2\n 3,2,1 -> 1,2,3\n 1,1,5 -> 1,5,1\n\n Solution: O(n)\n Processes: Take A = {1,3,2} as an example:\n            1. Traverse from back to forth, find the turning point, that is A[i] = 3.\n            2. Sort from the turning point to the end (A[i] to A[end]), so {3,2} becomes {2,3}.\n            3. If i equals to 0, finish! Else, goto 4.\n            4. Let j = i, search from A[j] to A[end] to find the first elem which is larger than A[i-1], '2' here.\n            5. Swap the elem A[j] with A[i-1].\n            Finally, the next permutation is {2,1,3}.\n */\n\nclass Solution {\npublic:\n    void nextPermutation(vector<int> &num) {\n        int n = num.size(), i = n - 1, j = 0;\n        while(i > 0 && num[i-1] >= num[i]) --i;\n        reverse(num.begin() + i,num.end());\n        if (i == 0) return;\n        while (i+j < n && num[i-1] >= num[i+j]) ++j;\n        swap(num[i-1], num[i+j]);\n    }\n};"
  },
  {
    "path": "PalindromeNumber.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 16, 2013\n Update:     Aug 22, 2013\n Problem:    Palindrome Number\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_9\n Notes:\n Determine whether an integer is a palindrome. Do this without extra space.\n Some hints:\n Could negative integers be palindromes? (ie, -1) (No!)\n If you are thinking of converting the integer to string, note the restriction of using extra space.\n You could also try reversing an integer. However, if you have solved the problem \"Reverse Integer\", \n you know that the reversed integer might overflow. How would you handle such case?\n There is a more generic way of solving this problem.\n\n Solution: 1. Count the number of digits first (traverse once) then check the digits from both sides to center.\n           2. Reverse the number, then check to see if x == reverse(x).\n           3. Recursion (interesting but a little hard to understand).\n */\n\nclass Solution {\npublic:\n    bool isPalindrome(int x) {\n        return isPalindrome1(x);\n    }\n    \n    // solution 1\n    bool isPalindrome1(int x) {\n        if (x < 0) return false;\n        int d = 1;\n        while (x / d >= 10) d *= 10;\n        while (d > 1)\n        {\n            if (x % 10 != x / d)\n                return false;\n            x = x % d / 10;\n            d /= 100;\n        }\n        return true;\n    }\n\n    // solution 2\n    bool isPalindrome2(int x) {\n        if (x < 0) return false;\n        return x == reverse(x);\n    }\n\n    int reverse(int x)\n    {\n        int rev = 0;\n        while (x) {\n            rev = rev * 10 + x % 10;\n            x /= 10;\n        }\n        return rev;\n    }\n    \n    // solution 3\n    bool isPalindrome3(int x) {\n        return isPalindromeRe(x, x);\n    }\n    \n    bool isPalindromeRe(int x, int &y) {\n        if (x < 0) return false;\n        if (x == 0) return true;\n        if (isPalindromeRe(x / 10, y) && x % 10 == y % 10)\n        {\n            y /= 10;\n            return true;\n        }\n        return false;\n    }\n};\n"
  },
  {
    "path": "PalindromePartitioning.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com : King, higuige@gmail.com\n Date:       May 20, 2013\n Update:     Oct 06, 2014\n Problem:    Palindrome Partitioning\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_131\n Notes:\n Given a string s, partition s such that every substring of the partition is a palindrome.\n Return all possible palindrome partitioning of s.\n For example, given s = \"aab\",\n Return\n [\n  [\"aa\",\"b\"],\n  [\"a\",\"a\",\"b\"]\n ]\n\n Solution: ...\n */\n\nclass Solution {\npublic:\n    vector<vector<string>> partition(string s) {\n        return partition_2(s);\n    }\n    vector<vector<string>> partition_2(string s) {\n        int size = s.size();\n        vector<vector<bool> > dp(size, vector<bool>(size));\n        for (int i = size - 1; i >= 0; --i) {\n            for (int j = i; j < size; ++j) {\n                dp[i][j]=(s[i]==s[j])&&(j<i+2||dp[i+1][j-1]);\n            }\n        }\n        vector<vector<string> > res[size];\n        for (int i = size - 1; i >= 0; --i) {\n            for (int j = i; j < size; ++j) {\n                if (dp[i][j] == false) continue;\n                string word = s.substr(i, j - i + 1);\n                if (j == size - 1) {\n                    res[i].push_back(vector<string>{word});\n                } else {\n                    for (auto iter : res[j+1]) {\n                        iter.insert(iter.begin(), word);\n                        res[i].push_back(iter);\n                    }\n                }\n            }\n        }\n        return res[0];\n    }\n\n    vector<vector<string>> partition_1(string s) {\n        int size = s.size();\n        vector<vector<bool> > dp(size, vector<bool>(size));\n        for (int i = size - 1; i >= 0; --i) {\n            for (int j = i; j < size; ++j) {\n                dp[i][j]=(s[i]==s[j])&&(j<i+2||dp[i+1][j-1]);\n            }\n        }\n        vector<vector<string> > res;\n        vector<string> path;\n        dfs(s, dp, 0, path, res);\n        return res;\n    }\n    void dfs(string s, vector<vector<bool> > &dp, int start, vector<string> &path, vector<vector<string> > &res) {\n        int size = s.size();\n        if (start == size) {\n            res.push_back(path);\n        }\n        for (int i = start; i < size; ++i) {\n            if (dp[start][i] == false) {\n                continue;\n            }\n            path.push_back(s.substr(start, i - start + 1));\n            dfs(s, dp, i + 1, path, res);\n            path.pop_back();\n        }\n    }\n};"
  },
  {
    "path": "PalindromePartitioningII.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       May 23, 2013\n Update:     Sep 23, 2013\n Problem:    Palindrome Partitioning II\n Difficulty: Hard\n Source:     http://leetcode.com/onlinejudge#question_132\n Notes:\n Given a string s, partition s such that every substring of the partition is a palindrome.\n Return the minimum cuts needed for a palindrome partitioning of s.\n For example, given s = \"aab\",\n Return 1 since the palindrome partitioning [\"aa\",\"b\"] could be produced using 1 cut.\n\n Solution: dp. Contributed by 孙冕. Great job:)\n */\n\nclass Solution {\npublic:\n    int minCut(string s) {\n        int size = s.size();\n        vector<int> dp(size + 1);\n        vector<bool> isP(size, true);\n        dp[size] = -1;\n        for (int i = size -1; i >= 0; --i) {\n            dp[i] = dp[i + 1] + 1;\n            for (int j = size - 1; j >= i; --j) {\n                isP[j] = false;\n                if (s[i] == s[j] && ( j - i < 2 || isP[j-1])) {\n                    isP[j] = true;\n                    dp[i] = min(dp[i], dp[j + 1] + 1);\n                }\n            }\n        }\n        return dp[0];\n    }\n};"
  },
  {
    "path": "PartitionList.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com : King, higuige@gmail.com\n Date:       Apr 9, 2013\n Update:     Oct 7, 2014\n Problem:    Partition List\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_86\n Notes:\n Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.\n You should preserve the original relative order of the nodes in each of the two partitions.\n For example,\n Given 1->4->3->2->5->2 and x = 3,\n return 1->2->2->4->3->5.\n\n Solution: ...\n */\n\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(int x) : val(x), next(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    ListNode *partition(ListNode *head, int x) {\n        ListNode leftdummy(-1);\n        ListNode rightdummy(-1);\n        ListNode * lhead = &leftdummy;\n        ListNode * rhead = &rightdummy;\n        \n        for(ListNode*cur = head; cur; cur=cur->next){\n            if(cur->val<x){\n                lhead->next = cur;\n                lhead = lhead->next;\n            }else{\n                rhead->next = cur;\n                rhead = rhead->next;\n            }\n        }\n        lhead->next = rightdummy.next;\n        rhead->next = nullptr;\n        return leftdummy.next;\n    }\n\n    ListNode *partition_1(ListNode *head, int x) {\n        ListNode dummy(0), *ins = &dummy, *cur = &dummy;\n        dummy.next = head;\n        while (cur->next) \n        {\n            if (cur->next->val >= x)\n            {\n                cur = cur->next;\n            } \n            else \n            {\n                if (cur == ins) \n                {\n                    cur = cur->next;\n                    ins = ins->next;\n                } \n                else \n                {\n                    ListNode *move = cur->next;\n                    cur->next = move->next;\n                    move->next = ins->next;\n                    ins->next = move;\n                    ins = move;\n                }\n            }\n        }\n        return dummy.next;\n    }\n};\n"
  },
  {
    "path": "Pascal'sTriangle.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 16, 2013\n Problem:    Pascal's Triangle\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_118\n Notes:\n Given numRows, generate the first numRows of Pascal's triangle.\n For example, given numRows = 5,\n Return\n [\n      [1],\n     [1,1],\n    [1,2,1],\n   [1,3,3,1],\n  [1,4,6,4,1]\n ]\n\n Solution: .....\n */\n\nclass Solution {\npublic:\n    vector<vector<int> > generate(int numRows) {\n        vector<vector<int> > res(numRows);\n        if (numRows < 1) return res;\n        res[0].push_back(1);\n        for (int i = 1; i < numRows; ++i)\n        {\n            res[i].push_back(1);\n            for (int j = 1; j < i; ++j)\n                res[i].push_back(res[i-1][j-1] + res[i-1][j]);\n            res[i].push_back(1);\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "Pascal'sTriangleII.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 16, 2013\n Problem:    Pascal's Triangle II\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_119\n Notes:\n Given an index k, return the kth row of the Pascal's triangle.\n For example, given k = 3,\n Return [1,3,3,1].\n Note:\n Could you optimize your algorithm to use only O(k) extra space?\n\n Solution: from back to forth...\n */\n\nclass Solution {\npublic:\n    vector<int> getRow(int rowIndex) {\n        vector<int> res(rowIndex+1, 1);\n        for (int i = 1; i <= rowIndex; ++i)\n            for (int j = i-1; j >= 1; --j)\n                res[j] += res[j-1];\n        return res;\n    }\n};"
  },
  {
    "path": "PathSum.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 6, 2013\n Update:     Jul 26, 2013\n Problem:    Path Sum\n Difficulty: easy\n Source:     http://www.leetcode.com/onlinejudge\n Notes:\n Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up \n all the values along the path equals the given sum.\n\n For example:\n Given the below binary tree and sum = 22,\n              5\n             / \\\n            4   8\n           /   / \\\n          11  13  4\n         /  \\      \\\n        7    2      1\n return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.\n \n Solution: Recursion.\n */\n\n/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    bool hasPathSum(TreeNode *root, int sum) {\n        if (!root)\n            return false;\n        if (!root->left and !root->right)\n            return sum == root->val;\n        return hasPathSum(root->left, sum - root->val) || \n               hasPathSum(root->right, sum - root->val);\n    }\n};\n"
  },
  {
    "path": "PathSum2.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com : King, higuige@gmail.com\n Date:       Apr 6, 2013\n Update:     Oct 7, 2014\n Problem:    Path Sum 2\n Difficulty: easy\n Source:     http://leetcode.com/onlinejudge#question_113\n Notes:\n Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.\n\n For example:\n Given the below binary tree and sum = 22,\n              5\n             / \\\n            4   8\n           /   / \\\n          11  13  4\n         /  \\    / \\\n        7    2  5   1\n return\n [\n   [5,4,11,2],\n   [5,8,4,5]\n ]\n \n Solution: DFS. \n */\n\n/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    vector<vector<int> > pathSum(TreeNode *root, int sum) {\n        vector<vector<int>> res;\n        vector<int> path;\n        pathSumRe(root, sum, res, path);\n        return res;\n    }\n    void pathSumRe(TreeNode *root, int sum, vector<vector<int>> &res, vector<int> &path)\n    {\n        if (!root) return;\n        path.push_back(root->val);\n        if (!root->left && !root->right && root->val == sum)\n        {\n            res.push_back(path);\n        }\n        pathSumRe(root->left, sum - root->val, res, path);\n        pathSumRe(root->right, sum - root->val, res, path);\n        path.pop_back();\n    }\n};\n"
  },
  {
    "path": "PermutationSequence.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       May 8, 2013\n Update:     Aug 12, 2013\n Problem:    Permutation Sequence\n Difficulty: Medium\n Source:     http://leetcode.com/onlinejudge#question_60\n Notes:\n The set [1,2,3,...,n] contains a total of n! unique permutations.\n By listing and labeling all of the permutations in order,\n We get the following sequence (ie, for n = 3):\n \"123\"\n \"132\"\n \"213\"\n \"231\"\n \"312\"\n \"321\"\n Given n and k, return the kth permutation sequence.\n Note: Given n will be between 1 and 9 inclusive.\n\n Solution: ...\n */\n\nclass Solution {\npublic:\n    string getPermutation(int n, int k) {\n        string num, res;\n        int total = 1;\n        for (int i = 1; i <= n; ++i)\n        {\n            num.push_back(i + '0');\n            total *= i;\n        }\n        k--;\n        while (n)\n        {\n            total /= n;\n            int i = k / total;\n            k %= total;\n            res.push_back(num[i]);\n            num.erase(i, 1);\n            n--;\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "Permutations.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 29, 2013\n Update:     Jul 19, 2013\n Problem:    Permutations\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_46\n Notes:\n Given a collection of numbers, return all possible permutations.\n For example,\n [1,2,3] have the following permutations:\n [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].\n\n Solution: dfs...\n */\n\nclass Solution {\npublic:\n    vector<vector<int>> res;\n\n    vector<vector<int>> permute(vector<int> &num) {\n        res.clear();\n        vector<bool> avail(num.size(), true);\n        vector<int> pum;\n        permuteRe(num, avail, pum);\n        return res;\n    }\n\n    void permuteRe(const vector<int> &num, vector<bool> &avail, vector<int> &pum)\n    {\n        if (pum.size() == num.size())\n        {\n            res.push_back(pum);\n            return;\n        }\n        for (int i = 0; i < num.size(); ++i)\n        {\n            if (avail[i])\n            {\n                avail[i] = false;\n                pum.push_back(num[i]);\n                permuteRe(num, avail, pum);\n                pum.pop_back();\n                avail[i] = true;\n            }\n        }\n    }\n};\n"
  },
  {
    "path": "PermutationsII.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 29, 2013\n Update:     Sep 2, 2013\n Problem:    Permutations II\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_47\n Notes:\n Given a collection of numbers that might contain duplicates, return all possible unique permutations.\n For example,\n [1,1,2] have the following unique permutations:\n [1,1,2], [1,2,1], and [2,1,1].\n\n Solution: dfs...\n */\n\nclass Solution {\npublic:\n    vector<vector<int>> res;\n    vector<vector<int>> permuteUnique(vector<int> &num) {\n        res.clear();\n        sort(num.begin(), num.end());\n        bool avail[num.size()];\n        memset(avail, true, sizeof(avail));\n        vector<int> pum;\n        permuteUniqueRe(num, pum, avail);\n        return res;\n    }\n\n    void permuteUniqueRe(vector<int> &num, vector<int> &pum, bool avail[])\n    {\n        if (pum.size() == num.size())\n        {\n            res.push_back(pum);\n            return;\n        }\n        int last_index = -1;\n        for (int i = 0; i < num.size(); ++i)\n        {\n            if (!avail[i]) continue;\n            if (last_index != -1 && num[i] == num[last_index]) continue;\n            \n            avail[i] = false;\n            pum.push_back(num[i]);\n            permuteUniqueRe(num, pum, avail);\n            pum.pop_back();\n            avail[i] = true;\n            last_index = i;\n        }\n    }\n};\n"
  },
  {
    "path": "PlusOne.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 9, 2013\n Update:     Aug 29, 2013\n Problem:    Plus One\n Difficulty: Easy\n Source:     https://oj.leetcode.com/problems/plus-one/\n Notes:\n Given a number represented as an array of digits, plus one to the number.\n\n Solution: ...\n */\n\nclass Solution {\npublic:\n    vector<int> plusOne(vector<int> &digits) {\n        int carry = 1, N = digits.size();\n        for (int i = N-1; i >= 0 && carry; --i)\n        {\n            int sum = carry + digits[i];\n            carry = sum / 10;\n            digits[i] = sum % 10;\n        }\n        if (carry > 0) {\n            digits.insert(digits.begin(), carry);\n        }\n        return digits;\n    }\n};\n"
  },
  {
    "path": "PopulatingNextRightPointersinEachNode.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com : King, higuige@gmail.com\n Date:       Apr 22, 2013\n Update:     Oct 7, 2014\n Problem:    Populating Next Right Pointers in Each Node\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_116\n Notes:\n Given a binary tree\n struct TreeLinkNode {\n    TreeLinkNode *left;\n    TreeLinkNode *right;\n    TreeLinkNode *next;\n }\n Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.\n Initially, all next pointers are set to NULL.\n Note:\n You may only use constant extra space.\n You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).\n For example,\n Given the following perfect binary tree,\n      1\n    /  \\\n   2    3\n  / \\  / \\\n 4  5  6  7\n After calling your function, the tree should look like:\n      1 -> NULL\n    /  \\\n   2 -> 3 -> NULL\n  / \\  / \\\n 4->5->6->7 -> NULL\n\n Solution: 1. Iterative: Two 'while' loops.\n           2. Iterative: Queue. Use extra space.\n           3. Recursive: DFS. Defect: Use extra stack space for recursion.\n */\n\n/**\n * Definition for binary tree with next pointer.\n * struct TreeLinkNode {\n *  int val;\n *  TreeLinkNode *left, *right, *next;\n *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    void connect(TreeLinkNode *root) {\n        connect_2(root);\n    }\n    void connect_1(TreeLinkNode *root) {\n        if (root == nullptr) return;\n        TreeLinkNode *cur = root;\n        TreeLinkNode dummy(-1);\n        TreeLinkNode *pre = &dummy;\n        while (cur) {\n            pre = &dummy;\n            pre->next = nullptr;\n            while (cur) {\n                if (cur->left) {\n                    pre->next = cur->left;\n                    pre = pre->next;\n                }\n                if (cur->right) {\n                    pre->next = cur->right;\n                    pre = pre->next;\n                }\n                cur = cur->next;\n            }\n            cur = dummy.next;\n        }\n    }\n    void connect_2(TreeLinkNode *root) {\n        if (root == NULL) return;\n        queue<TreeLinkNode *> q;\n        q.push(root);\n        q.push(NULL);\n        TreeLinkNode *last = NULL;\n        TreeLinkNode dummy(-1);\n        TreeLinkNode *pre = &dummy;\n        while (!q.empty()) {\n            TreeLinkNode *node = q.front();\n            q.pop();\n            if (node == NULL) {\n                if (dummy.next) q.push(NULL);\n                pre = &dummy;\n                pre->next = NULL;\n            } else {\n                pre->next = node;\n                pre = pre->next;\n                if (node->left) q.push(node->left);\n                if (node->right) q.push(node->right);\n            }\n        }\n    }\n    void connect_3(TreeLinkNode *root) {\n        if (root == nullptr) return;\n        TreeLinkNode dummy(-1);\n        TreeLinkNode *pre = &dummy;\n        TreeLinkNode *cur = root;\n        while (cur) {\n            if (cur->left) {\n                pre->next = cur->left;\n                pre = pre->next;\n            }\n            if (cur->right) {\n                pre->next = cur->right;\n                pre = pre->next;\n            }\n            cur = cur->next;\n        }\n        connect(dummy.next);\n    }\n};"
  },
  {
    "path": "PopulatingNextRightPointersinEachNodeII.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com : King, higuige@gmail.com\n Date:       Apr 23, 2013\n Update:     Oct 7, 2014\n Problem:    Populating Next Right Pointers in Each Node II\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_117\n Notes:\n Follow up for problem \"Populating Next Right Pointers in Each Node\".\n What if the given tree could be any binary tree? Would your previous solution still work?\n Note:\n You may only use constant extra space.\n For example,\n Given the following binary tree,\n     1\n    /  \\\n   2    3\n  / \\    \\\n 4   5    7\n After calling your function, the tree should look like:\n     1 -> NULL\n    /  \\\n   2 -> 3 -> NULL\n  / \\    \\\n 4-> 5 -> 7 -> NULL\n\n Solution: 1. iterative way with CONSTANT extra space.\n           2. iterative way + queue. Contributed by SUN Mian(孙冕).\n           3. recursive solution.\n */\n\n/**\n * Definition for binary tree with next pointer.\n * struct TreeLinkNode {\n *  int val;\n *  TreeLinkNode *left, *right, *next;\n *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    void connect(TreeLinkNode *root) {\n        connect_2(root);\n    }\n    void connect_1(TreeLinkNode *root) {\n        if (root == nullptr) return;\n        TreeLinkNode *cur = root;\n        TreeLinkNode dummy(-1);\n        TreeLinkNode *pre = &dummy;\n        while (cur) {\n            pre = &dummy;\n            pre->next = nullptr;\n            while (cur) {\n                if (cur->left) {\n                    pre->next = cur->left;\n                    pre = pre->next;\n                }\n                if (cur->right) {\n                    pre->next = cur->right;\n                    pre = pre->next;\n                }\n                cur = cur->next;\n            }\n            cur = dummy.next;\n        }\n    }\n    void connect_2(TreeLinkNode *root) {\n        if (root == NULL) return;\n        queue<TreeLinkNode *> q;\n        q.push(root);\n        q.push(NULL);\n        TreeLinkNode *last = NULL;\n        TreeLinkNode dummy(-1);\n        TreeLinkNode *pre = &dummy;\n        while (!q.empty()) {\n            TreeLinkNode *node = q.front();\n            q.pop();\n            if (node == NULL) {\n                if (dummy.next) q.push(NULL);\n                pre = &dummy;\n                pre->next = NULL;\n            } else {\n                pre->next = node;\n                pre = pre->next;\n                if (node->left) q.push(node->left);\n                if (node->right) q.push(node->right);\n            }\n        }\n    }\n    void connect_3(TreeLinkNode *root) {\n        if (root == nullptr) return;\n        TreeLinkNode dummy(-1);\n        TreeLinkNode *pre = &dummy;\n        TreeLinkNode *cur = root;\n        while (cur) {\n            if (cur->left) {\n                pre->next = cur->left;\n                pre = pre->next;\n            }\n            if (cur->right) {\n                pre->next = cur->right;\n                pre = pre->next;\n            }\n            cur = cur->next;\n        }\n        connect(dummy.next);\n    }\n};"
  },
  {
    "path": "Pow(x,n).h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 6, 2013\n Update:     Jul 15, 2013\n Problem:    Pow(x, n)\n Difficulty: easy\n Source:     http://leetcode.com/onlinejudge#question_50\n Notes:\n Implement pow(x, n).\n \n Solution: recursion.\n */\n\nclass Solution {\npublic:\n    double pow(double x, int n) {\n        if (x < 0) return (n % 2 == 0) ? pow(-x, n) : -pow(-x, n);\n        if (x == 0 || x == 1) return x;\n        if (n < 0) return 1.0 / pow(x, -n);\n        if (n == 0) return 1.0;\n        \n        double half = pow(x, n / 2);\n        if (n % 2 == 0) return half * half;\n        else return x * half * half;\n    }\n};\n"
  },
  {
    "path": "README.md",
    "content": "# LeetCode\n\n\nSolve problems from [Leetcode](http://oj.leetcode.com/). All the codes are tested using online-judge.\n\nHere is a [difficulty and frequency distribution chart](http://wwwx.cs.unc.edu/~zhew/Leetcoder/) for each problem, which I got from the Internet and is very useful. Feel free to make pull request for adding the [difficulty and frequency for new problems here](https://github.com/leetcoders/Leetcoder).\n\nPlease feel free to let me know if you have any problem or better solutions:)\n\n**Note**: The problem link in the file will take you to the Old OJ, which will expire on October 12, 12pm PST.<br>\nYou may use [this link](http://oj.leetcode.com/) to the new OJ instead!\n"
  },
  {
    "path": "RecoverBinarySearchTree.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Jun 15, 2013\n Problem:    Recover Binary Search Tree\n Difficulty: High\n Source:     http://leetcode.com/onlinejudge#question_99\n Notes:\n Two elements of a binary search tree (BST) are swapped by mistake.\n Recover the tree without changing its structure.\n Note:\n A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?\n\n Solution: 1. recursive solution. O(n) space. get inorder list first.\n           2. recursive solution. O(n) space. with only auxiliary two pointers.\n           3. Morris inorder traversal. O(1) space. with only auxiliary two pointers.\n*/\n\nstruct TreeNode {\n    int val;\n    TreeNode *left;\n    TreeNode *right;\n    TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n};\n\nclass Solution {\npublic:\n    // first solution\n    void recoverTree_1(TreeNode *root) {\n        vector<TreeNode *> inorder;\n        inorderTraversal(root, inorder);\n        TreeNode *first = NULL, *second = NULL;\n        for (int i = 1; i < inorder.size(); ++i)\n        {\n            if (inorder[i-1]->val < inorder[i]->val)\n                continue;\n            if (!first)\n                first = inorder[i-1];\n            second = inorder[i];\n        }\n        swap(first->val, second->val);\n    }\n\n    void inorderTraversal(TreeNode *root, vector<TreeNode *> &inorder) {\n        if (!root) return;\n        inorderTraversal(root->left, inorder);\n        inorder.push_back(root);\n        inorderTraversal(root->right, inorder);\n    }\n\n    // second solution\n    void recoverTree_2(TreeNode *root) {\n        TreeNode *prev = NULL, *first = NULL, *second = NULL;\n        recoverTreeRe(root, prev, first, second);\n        swap(first->val, second->val);\n    }\n\n    void recoverTreeRe(TreeNode *curNode, TreeNode *&preNode, TreeNode *&first, TreeNode *&second) {\n        if (curNode == NULL) return;\n        recoverTreeRe(curNode->left, preNode, first, second);\n        if (preNode && preNode->val > curNode->val) {\n            if (first == NULL) \n                first = preNode;\n            second = curNode;\n        }\n        preNode = curNode;\n        recoverTreeRe(curNode->right, preNode, first, second);\n    }\n    \n    // third solution\n    void recoverTree_3(TreeNode *root) {\n        TreeNode *cur = root, *prev = NULL;\n        TreeNode *first = NULL, *second = NULL, *last = NULL;\n        while (cur != NULL)\n        {\n            if (cur->left == NULL)\n            {\n                compare(last, cur, first, second);\n                last = cur;\n                cur = cur->right;\n            }\n            else\n            {\n                prev = cur->left;\n                while (prev->right != NULL && prev->right != cur)\n                    prev = prev->right;\n\n                if (prev->right == NULL)\n                {\n                    prev->right = cur;\n                    cur = cur->left;\n                }\n                else\n                {\n                    compare(last, cur, first, second);\n                    last = cur;\n                    prev->right = NULL;\n                    cur = cur->right;\n                }\n            }\n        }\n        swap(first->val, second->val);\n    }\n\n    void compare(TreeNode *last, TreeNode *cur, TreeNode *&first, TreeNode *&second)\n    {\n        if (last && last->val > cur->val)\n        {\n            if (!first)\n                first = last;\n            second = cur;\n        }\n    }\n};"
  },
  {
    "path": "RegularExpressionMatching.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Co-author:  King, higuige@gmail.com\n Date:       May 26, 2013\n Update:     Oct 26, 2014\n Problem:    Regular Expression Matching\n Difficulty: Hard\n Source:     http://leetcode.com/onlinejudge#question_10\n Notes:\n Implement regular expression matching with support for '.' and '*'.\n '.' Matches any single character.\n '*' Matches zero or more of the preceding element.\n The matching should cover the entire input string (not partial).\n The function prototype should be:\n bool isMatch(const char *s, const char *p)\n Some examples:\n isMatch(\"aa\",\"a\") ? false\n isMatch(\"aa\",\"aa\") ? true\n isMatch(\"aaa\",\"aa\") ? false\n isMatch(\"aa\", \"a*\") ? true\n isMatch(\"aa\", \".*\") ? true\n isMatch(\"ab\", \".*\") ? true\n isMatch(\"aab\", \"c*a*b\") ? true\n\n Solution: Both of the two solutions are from http://leetcode.com/2011/09/regular-expression-matching.html .\n Solution 3: DP.\n Solution 4: DP. O(n^2) Time, O(n) Space.\n*/\n\nclass Solution {\npublic:\n    bool isMatch(const char *s, const char *p) {\n        if (*p == '\\0') return *s == '\\0';\n        \n        if (*(p+1) == '*') // next is '*'\n        {\n            while ((*s == *p || *p == '.') && *s != '\\0')\n            {\n                if (isMatch(s, p+2))\n                    return true;\n                s++;\n            }\n            return isMatch(s, p+2);\n        }\n        \n        if (*s == '\\0') return false;\n        return (*s == *p || *p == '.') && isMatch(s+1, p+1);\n    }\n    \n    bool isMatch_2(const char *s, const char *p) {\n        if (*p == '\\0') return *s == '\\0';\n        if ((*s != '\\0') && (*s == *p || *p =='.')) {\n            if (*(p+1) == '*') {\n                return isMatch(s+1,p) || isMatch(s, p+2);\n            } else return isMatch(s+1, p+1);\n        }\n        return *(p+1) == '*' && isMatch(s, p+2);\n    }\n\n    bool isMatch_3(const char *s, const char *p) {\n         int l1 = strlen(s), l2 = strlen(p), k;\n         char ch1, ch2;\n         vector<vector<bool> > f(l1 + 1, vector<bool>(l2 + 1,false));\n         f[0][0] = true;\n         for (int i = 2; i <= l2; i ++)\n            if (*(p + i - 1) == '*') f[0][i] = f[0][i - 2];\n         for (int i = 1; i <= l1; i ++)\n            for (int j = 1; j <= l2; j ++) {\n                ch1 = *(s + i - 1); ch2 = *(p + j - 1);\n                if (ch2 != '*') f[i][j] = f[i - 1][j - 1] && (ch1 == ch2 || ch2 == '.');\n                else {\n                    f[i][j] = f[i][j - 2];\n                    if (*(s + i - 1) == *(p + j - 2) || *(p + j - 2) == '.') f[i][j] = f[i][j] | f[i - 1][j];\n                }\n            }\n         return f[l1][l2];\n    }\n    bool isMatch_4(const char *s, const char *p) {\n        int l1 = strlen(s), l2 = strlen(p), k;\n        char ch1, ch2;\n        vector<vector<bool> > f(2, vector<bool>(l2 + 1,false));\n        f[0][0] = true;\n        for (int i = 2; i <= l2; i ++)\n            if (*(p + i - 1) == '*') f[0][i] = f[0][i - 2];\n        for (int i = 1; i <= l1; i ++){\n            for (int j = 1; j <= l2; j ++) {\n                ch1 = *(s + i - 1); ch2 = *(p + j - 1);\n                if (ch2 != '*') f[1][j] = f[0][j - 1] && (ch1 == ch2 || ch2 == '.');\n                else {\n                    f[1][j] = f[1][j - 2];\n                    if (*(s + i - 1) == *(p + j - 2) || *(p + j - 2) == '.') f[1][j] = f[1][j] | f[0][j];\n                }\n            }\n            f[0] = f[1];\n        }\n        return f[0][l2];\n    }\n};\n"
  },
  {
    "path": "RemoveDuplicatesfromSortedArray.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 10, 2013\n Update:     Jul 16, 2013\n Problem:    Remove Duplicates from Sorted Array\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_26\n Notes:\n Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.\n Do not allocate extra space for another array, you must do this in place with constant memory.\n For example,\n Given input array A = [1,1,2],\n Your function should return length = 2, and A is now [1,2].\n\n Solution: Update 7/16/2013: Let j start from 0 for better understanding.\n */\n\nclass Solution {\npublic:\n    int removeDuplicates(int A[], int n) {\n        int j = 0;\n        for (int i = 0; i < n; ++i)\n            if (i == 0 || A[i] != A[i-1])\n                A[j++] = A[i];\n        return j;\n    }\n};"
  },
  {
    "path": "RemoveDuplicatesfromSortedArrayII.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 10, 2013\n Update:     Jul 16, 2013 [Two pointers ('last' and 'lastlast').]\n Problem:    Remove Duplicates from Sorted Array II\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_80\n Notes:\n Follow up for \"Remove Duplicates\":\n What if duplicates are allowed at most twice?\n For example,\n Given sorted array A = [1,1,1,2,2,3],\n Your function should return length = 5, and A is now [1,1,2,2,3].\n\n Solution: ...\n */\n\nclass Solution {\npublic:\n    int removeDuplicates(int A[], int n) {\n        if (n <= 2) return n;\n        int j = 2;\n        for (int i = 2; i < n; ++i)\n            if (A[i] != A[j-2])\n                A[j++] = A[i];\n        return j;\n    }\n};"
  },
  {
    "path": "RemoveDuplicatesfromSortedList.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 10, 2013\n Update:     Jul 17, 2013 (Add solution 2)\n Problem:    Remove Duplicates from Sorted List\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_83\n Notes:\n Given a sorted linked list, delete all duplicates such that each element appear only once.\n For example,\n Given 1->1->2, return 1->2.\n Given 1->1->2->3->3, return 1->2->3.\n\n Solution: 1. Delete duplicates directly.\n           2. Copy value first (like Remove Duplicates from Array) and then delete the remaining elements.\n */\n\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(int x) : val(x), next(NULL) {}\n * };\n */\n\nclass Solution {\npublic:\n    ListNode *deleteDuplicates(ListNode *head) {\n        return deleteDuplicates_1(head);\n    }\n    \n    ListNode *deleteDuplicates_1(ListNode *head) {\n        if (!head) return head;\n        ListNode *cur = head;\n        while (cur->next)\n        {\n            if (cur->val == cur->next->val)\n            {\n                ListNode *del = cur->next;\n                cur->next = del->next;\n                delete del;\n            }\n            else\n            {\n                cur = cur->next;\n            }\n        }\n        return head;\n    }\n    \n    ListNode *deleteDuplicates_2(ListNode *head) {\n        if (!head) return head;\n        ListNode *last = head, *cur = head->next;\n        while (cur)\n        {\n            if (last->val != cur->val) {\n                last = last->next;\n                last->val = cur->val;\n            }\n            cur = cur->next;\n        }\n        cur = last->next;\n        while (cur) {\n            ListNode *del = cur;\n            cur = cur->next;\n            delete del;\n        }\n        last->next = NULL;\n        return head;\n    }\n};\n"
  },
  {
    "path": "RemoveDuplicatesfromSortedListII.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 10, 2013\n Update:     Dec 12, 2014\n Problem:    Remove Duplicates from Sorted List II\n Difficulty: Easy\n Source:     https://oj.leetcode.com/problems/remove-duplicates-from-sorted-list-ii/\n Notes:\n Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.\n For example,\n Given 1->2->3->3->4->4->5, return 1->2->5.\n Given 1->1->1->2->3, return 2->3.\n\n Solution: 1. iterative 2. recursive\n */\n\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(int x) : val(x), next(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    ListNode *deleteDuplicates(ListNode *head) {\n        return deleteDuplicates_1(head);\n    }\n    \n    ListNode *deleteDuplicates_1(ListNode *head) {\n        if(NULL==head||NULL==head->next) return head;\n        ListNode dummy(-1);\n        ListNode * pre = &dummy;\n        while(head!=NULL){\n            if(head->next&&head->val==head->next->val){\n                while(head->next&&head->val==head->next->val) {\n                    ListNode *del = head;\n                    head = head->next;\n                    delete del;\n                }\n            }else{\n                pre->next = head;\n                pre = pre->next;\n            }\n            head = head->next;\n        }\n        pre->next = NULL;\n        return dummy.next;\n    }\n    \n    ListNode *deleteDuplicates_2(ListNode *head) {\n        if (!head) return NULL;\n        if (!head->next || head->val != head->next->val) {\n            head->next = deleteDuplicates(head->next);\n            return head;\n        }\n        int val = head->val;\n        while(head->next&&head->val==head->next->val) {\n            ListNode *del = head;\n            head = head->next;\n            delete del;\n        }\n        return deleteDuplicates(head->next);\n    }\n};"
  },
  {
    "path": "RemoveElement.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 10, 2013\n Update:     Jul 20, 2013\n Problem:    Remove Element\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_27\n Notes:\n Given an array and a value, remove all instances of that value in place and return the new length.\n The order of elements can be changed. It doesn't matter what you leave beyond the new length.\n\n Solution: Refactor: Update solution. Use two pointers.\n */\n\nclass Solution {\npublic:\n    int removeElement(int A[], int n, int elem) {\n        int i = 0;\n        for (int j = 0; j < n; ++j)\n            if (A[j] != elem)\n                A[i++] = A[j];\n        return i;\n    }\n};\n"
  },
  {
    "path": "RemoveNthNodeFromEndofList.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 10, 2013\n Update:     Sep 27, 2013\n Problem:    Remove Nth Node From End of List\n Difficulty: Medium\n Source:     http://leetcode.com/onlinejudge#question_19\n Notes:\n Given a linked list, remove the nth node from the end of list and return its head.\n For example,\n Given linked list: 1->2->3->4->5, and n = 2.\n After removing the second node from the end, the linked list becomes 1->2->3->5.\n Note:\n Given n will always be valid.\n Try to do this in one pass.\n\n Solution: head---back------front------>NULL\n                   |          |\n                   ---> n <----\n */\n\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(int x) : val(x), next(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    ListNode *removeNthFromEnd(ListNode *head, int n) {\n        ListNode dummy(0), *back = &dummy, *front = &dummy;\n        dummy.next = head;\n        while (n--) front = front->next;\n        while (front->next) {\n            front = front->next;\n            back = back->next;\n        }\n        ListNode *del = back->next;\n        back->next = del->next;\n        delete del;\n        return dummy.next;\n    }\n    ListNode *removeNthFromEnd_2(ListNode *head, int n) {\n        if(head==NULL) return head;\n        ListNode *slow = head, *fast = head;\n        while(n--) fast = fast->next;\n        if (fast == NULL) return head->next;\n        while(fast->next) {\n            fast = fast->next;\n            slow = slow->next;\n        }\n        slow->next = slow->next->next;\n        return head;\n    }\n};"
  },
  {
    "path": "ReorderList.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Nov 11, 2013\n Problem:    Reorder List\n Difficulty: Easy\n Source:     http://oj.leetcode.com/problems/reorder-list/\n Notes:\n Given a singly linked list L: L0->L1->...->Ln-1->Ln,\n reorder it to: L0->Ln->L1->Ln-1->L2->Ln-2->...\n You must do this in-place without altering the nodes' values.\n For example,\n Given {1,2,3,4}, reorder it to {1,4,2,3}.\n\n Solution: Reverse the back half first, then reorder.\n*/\n\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(int x) : val(x), next(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    void reorderList(ListNode *head) {\n        if (!head || !head->next) return;\n        ListNode *slow = head, *fast = head->next->next;\n        while (fast && fast->next) {\n            fast = fast->next->next;\n            slow = slow->next;\n        }\n        if (fast) slow = slow->next;\n        ListNode *mid = slow, *cur = slow->next;\n        while (cur->next) {\n            ListNode *mov = cur->next;\n            cur->next = mov->next;\n            mov->next = mid->next;\n            mid->next = mov;\n        }\n        cur = head;\n        while (cur != mid && mid->next) {\n            ListNode *mov = mid->next;\n            mid->next = mov->next;\n            mov->next = cur->next;\n            cur->next = mov;\n            cur = cur->next->next;\n        }\n    }\n};"
  },
  {
    "path": "RepeatedDNASequences.h",
    "content": "/*\n Author:     Andy, nkuwjg@gmail.com\n Date:       Feb 3, 2015\n Problem:    Repeated DNA Sequences\n Difficulty: Easy\n Source:     https://oj.leetcode.com/problems/repeated-dna-sequences/\n Notes:\nAll DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, for example: \"ACGAATTCCG\". When studying DNA, it is sometimes useful to identify repeated sequences within the DNA.\n\nWrite a function to find all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule.\n\nFor example,\n\nGiven s = \"AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT\",\n\nReturn:\n[\"AAAAACCCCC\", \"CCCCCAAAAA\"].\n\n Solution: ...\n */\n\nclass Solution {\npublic:\n    vector<string> findRepeatedDnaSequences(string s) {\n        vector<string> res;\n        map<int,int> m;\n        map<char,int> mole;\n        mole['A'] = 0; mole['C'] = 1; mole['G'] = 2; mole['T'] = 3;\n        if (s.length() < 11) return res;\n        int x = 0, i = 0, mask = (1<<20) - 1;\n        for (; i < 10; ++i) {\n            x = (x<<2) | mole[s[i]];\n        }\n        m[x] = 1;\n        for (; i < s.length(); ++i) {\n            x = mask & ((x<<2) | mole[s[i]]);\n            if (++m[x] == 2) {\n                res.push_back(convert2Str(x));\n            } \n        }\n        return res;\n    }\n    string convert2Str(int x) {\n        string res;\n        for (int i = 0; i < 10; ++i) {\n            int k = x & 3;\n            if (k == 0) res = 'A' + res;\n            if (k == 1) res = 'C' + res;\n            if (k == 2) res = 'G' + res;\n            if (k == 3) res = 'T' + res;\n            x = x >> 2;\n        }\n        return res;\n    }\n};"
  },
  {
    "path": "RestoreIPAddresses.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       May 1, 2013\n Update:     Jul 26, 2013\n Problem:    Restore IP Addresses\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_93\n Notes:\n Given a string containing only digits, restore it by returning all possible valid IP address combinations.\n For example:\n Given \"25525511135\",\n return [\"255.255.11.135\", \"255.255.111.35\"]. (Order does not matter)\n\n Solution: DFS.\n */\n\nclass Solution {\npublic:\n    vector<string> restoreIpAddresses(string s) {\n        vector<string> res;\n        string ip;\n        restoreIpAddressRe(s, res, ip, 0, 0);\n        return res;\n    }\n    \n    void restoreIpAddressRe(string &s, vector<string> &res, string &ip, int deep, int start)\n    {\n        if (deep == 4 && start == s.size())\n            res.push_back(ip);\n        if (deep == 4) return;\n        \n        int num = 0, origSize = ip.size();\n        if (origSize != 0) ip.push_back('.');\n        for (int i = start; i < s.size(); ++i)\n        {\n            num = num * 10 + s[i] - '0';\n            if (num > 255) break;\n            ip.push_back(s[i]);\n            restoreIpAddressRe(s, res, ip, deep + 1, i + 1);\n            if (num == 0) break;\n        }\n        ip.resize(origSize);\n    }\n};"
  },
  {
    "path": "ReverseInteger.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 7, 2013\n Update:     Dec 14, 2014 (By wangjingui@outlook.com)\n Problem:    Reverse Integer\n Difficulty: Easy\n Source:     https://oj.leetcode.com/problems/reverse-integer/\n Notes:\n Reverse digits of an integer.\n Example1: x = 123, return 321\n Example2: x = -123, return -321\n\n Have you thought about this?\n Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!\n If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.\n Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?\n Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).\n\n Solution: Use % and / iteratively.\n */\nclass Solution {\npublic:\n    int reverse(int x) {\n        long long res = 0;\n        while (x) {\n            res = res * 10 + (x % 10);\n            x /= 10;\n        }\n        if (res < INT_MIN || res > INT_MAX) return 0;\n        return res;\n    }\n};\n"
  },
  {
    "path": "ReverseLinkedListII.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 9, 2013\n Update:     Jul 28, 2013\n Problem:    Reverse Linked List II\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_92\n Notes:\n Reverse a linked list from position m to n. Do it in-place and in one-pass.\n For example:\n Given 1->2->3->4->5->NULL, m = 2 and n = 4,\n return 1->4->3->2->5->NULL.\n Note:\n Given m, n satisfy the following condition:\n 1 <= m <= n <= length of list.\n\n Solution: in-place & one-pass.\n */\n\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(int x) : val(x), next(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    ListNode *reverseBetween(ListNode *head, int m, int n) {\n        ListNode dummy(0), *ins = &dummy;\n        dummy.next = head;\n        for (int i = 0; i < m-1; ++i)\n            ins = ins->next;\n        ListNode *cur = ins->next;\n        for (int i = 0; i < n-m; ++i) {\n            ListNode *move = cur->next;\n            cur->next = move->next;\n            move->next = ins->next;\n            ins->next = move;\n        }\n        return dummy.next;\n    }\n};"
  },
  {
    "path": "ReverseNodesinkGroup.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 18, 2013\n Update:     Jul 20, 2013\n Problem:    Reverse Nodes in k-Group\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_25\n Notes:\n Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.\n If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.\n You may not alter the values in the nodes, only nodes itself may be changed.\n Only constant memory is allowed.\n For example,\n Given this linked list: 1->2->3->4->5\n For k = 2, you should return: 2->1->4->3->5\n For k = 3, you should return: 3->2->1->4->5\n\n Solution: ...\n */\n\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(int x) : val(x), next(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    ListNode *reverseKGroup(ListNode *head, int k) {\n        if (k <= 1) return head;\n        int reverseTimes = GetLength(head) / k;\n        ListNode dummy(0); dummy.next = head;\n        ListNode *ins = &dummy, *cur = ins->next;\n        while (reverseTimes--) \n        {\n            for (int i = 0; i < k - 1; ++i) {\n                ListNode *move = cur->next;\n                cur->next = move->next;\n                move->next = ins->next;\n                ins->next = move;\n            }\n            ins = cur;\n            cur = ins->next;\n        }\n        return dummy.next;\n    }\n\n    int GetLength(ListNode *head) {\n        int length = 0;\n        while (head) {\n            head = head->next;\n            length++;\n        }\n        return length;\n    }\n};"
  },
  {
    "path": "ReverseWordsInAString.h",
    "content": "/*\n Author:     King, wangjingui@outlook.com\n Date:       Dec 13, 2014\n Problem:    Reverse Words in a String \n Difficulty: Easy\n Source:     https://oj.leetcode.com/problems/reverse-words-in-a-string/\n Notes:\n Given an input string, reverse the string word by word.\n\n For example,\n Given s = \"the sky is blue\",\n return \"blue is sky the\".\n\n Solution: 1. Reverse the raw string and reverse each word.\n           2. In Place.\n*/\n\nclass Solution {\npublic:\n    void reverseWords_1(string &s) {\n        string res;\n        reverse(s.begin(),s.end());\n        for (int i = 0; i < s.size(); ++i) {\n            while (i < s.size() && s[i] == ' ') ++i;\n            if(i == s.size()) break;\n            string tmp;\n            while(i < s.size() && s[i] != ' ') tmp.push_back(s[i++]);\n            reverse(tmp.begin(), tmp.end());\n            if (!res.empty()) res = res + \" \" + tmp;\n            else res = res + tmp;\n        }\n        s = res;\n    }\n    void reverseWords_2(string &s) {\n        int N = s.size();\n        reverse(s.begin(),s.end());\n        for (string::iterator i = s.begin(); i != s.end();) {\n            while (i != s.end() && *i == ' ') ++i;\n            string::iterator left = i;\n            while((i) != s.end() && *(i) != ' ') ++i;\n            reverse(left,i);\n        }\n        int idx = 0;\n        for (int i = 0; i < N;) {\n            while (i < N && s[i] == ' ') ++i;\n            while (i < N && s[i] != ' ') s[idx++] = s[i++];\n            while (i < N && s[i] == ' ') ++i;\n            if (i == N) break;\n            s[idx++] = ' ';\n        }\n        s.resize(idx);\n    }\n};"
  },
  {
    "path": "RomantoInteger.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       May 13, 2013\n Update:     Sep 22, 2013\n Problem:    Roman to Integer\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_13\n Notes:\n Given a roman numeral, convert it to an integer.\n Input is guaranteed to be within the range from 1 to 3999.\n\n Solution: use <map> or <unordered_map> (clean)\n */\n\nclass Solution {\npublic:\n    int romanToInt(string s) {\n        unordered_map<char, int> roman;\n        roman['M'] = 1000;\n        roman['D'] = 500;\n        roman['C'] = 100;\n        roman['L'] = 50;\n        roman['X'] = 10;\n        roman['V'] = 5;\n        roman['I'] = 1;\n\n        int res = 0, N = s.size();\n        for (int i = 0; i < N; ++i)\n        {\n            if (i < N-1 && roman[s[i]] < roman[s[i+1]])\n                res -= roman[s[i]];\n            else\n                res += roman[s[i]];\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "RotateImage.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 9, 2013\n Update:     Jul 21, 2013 (Add solution 2)\n Problem:    Rotate Image\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_48\n Notes:\n You are given an n x n 2D matrix representing an image.\n Rotate the image by 90 degrees (clockwise).\n Follow up:\n Could you do this in-place?\n\n Solution: 1. Rotate one-fourth of the image clockwise.\n           2. 123   ->  147   ->   741    (preferable)\n              456       258        852\n              789       369        963\n */\n\nclass Solution {\npublic:\n    void rotate(vector<vector<int> > &matrix) {\n        rotate_2(matrix);\n    }\n    \n    void rotate_1(vector<vector<int> > &matrix) {\n        int n = matrix.size();\n        for (int i = 0; i < (n + 1) / 2; i++)\n            for (int j = 0; j < n / 2; j++)\n                rotateElement(matrix, i, j);\n    }\n    void rotateElement(vector<vector<int> > &matrix, int row, int col)\n    {\n        int temp = matrix[row][col];\n        for (int i = 0; i < 3; i++)\n        {\n            int c = row;\n            int r = matrix.size() - 1 - col;\n            matrix[row][col] = matrix[r][c];\n            row = r;\n            col = c;\n        }\n        matrix[row][col] = temp;\n    }\n    \n    void rotate_2(vector<vector<int> > &matrix) {\n        int N = matrix.size();\n        for (int i = 0; i < N; ++i)\n            for (int j = i+1; j < N; ++j)\n                swap(matrix[i][j], matrix[j][i]);\n        for (int j = 0; j < N/2; ++j)\n            for (int i = 0; i < N; ++i)\n                swap(matrix[i][j], matrix[i][N-j-1]);\n    }\n};\n"
  },
  {
    "path": "RotateList.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 8, 2013\n Problem:    Rotate List\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_61\n Notes:\n Given a list, rotate the list to the right by k places, where k is non-negative.\n\n For example:\n Given 1->2->3->4->5->NULL and k = 2,\n return 4->5->1->2->3->NULL.\n\n Solution: Notice that k can be larger than the list size (k % list_size).\n           This solution traverses the list twice at most.\n*/\n\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(int x) : val(x), next(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    ListNode *rotateRight(ListNode *head, int k) {\n        if (!head) return NULL;\n        \n        ListNode* tail = head;\n        int count = 1;\n        while (tail->next)\n        {\n            tail = tail->next;\n            count++;\n        }\n        k = k % count;   // in case the list rotates more than one round.\n        if (k == 0) return head;\n        \n        ListNode* cur = head;\n        for (int i = 0; i < count - k - 1; i++)\n            cur = cur->next;\n        \n        ListNode* newHead = cur->next;\n        cur->next = NULL;\n        tail->next = head;\n        \n        return newHead;\n    }\n};"
  },
  {
    "path": "SameTree.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 7, 2013\n Problem:    Same Tree\n Difficulty: easy\n Source:     http://leetcode.com/onlinejudge#question_100\n Notes:\n Given two binary trees, write a function to check if they are equal or not.\n Two binary trees are considered equal if they are structurally identical and the nodes have the same value.\n\n Solution: recursion.\n */\n\n/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    bool isSameTree(TreeNode *p, TreeNode *q) {\n        if (!p && !q) return true;\n        if (p && !q || !p && q) return false;\n        if (p->val != q->val) return false;\n        \n        return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);\n    }\n};"
  },
  {
    "path": "ScrambleString.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Jul 12, 2013\n Update:     Sep 13, 2013\n Problem:    Scramble String\n Difficulty: Medium\n Source:     http://leetcode.com/onlinejudge#question_87\n Notes:\n Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively.\n Below is one possible representation of s1 = \"great\":\n       great\n      /     \\\n     gr    eat\n    / \\    /  \\\n   g   r  e   at\n  / \\\n a   t\n To scramble the string, we may choose any non-leaf node and swap its two children.\n For example, if we choose the node \"gr\" and swap its two children, it produces a scrambled string \"rgeat\".\n       rgeat\n      /     \\\n     rg    eat\n    / \\    /  \\\n   r   g  e   at\n  / \\\n a   t\n We say that \"rgeat\" is a scrambled string of \"great\".\n Similarly, if we continue to swap the children of nodes \"eat\" and \"at\", it produces a scrambled string \"rgtae\".\n      rgtae\n      /    \\\n     rg    tae\n    / \\    /  \\\n   r   g  ta  e\n  / \\\n t   a\n We say that \"rgtae\" is a scrambled string of \"great\".\n Given two strings s1 and s2 of the same length, determine if s2 is a scrambled string of s1.\n\n Solution: 1. 3-dimensional dp. Contributed by yinlinglin. I really appreciate it!\n              'dp[k][i][j] == true' means string s1(start from i, length k) is a scrambled string of \n              string s2(start from j, length k).\n           2. Recursion + pruning.\n */\n\nclass Solution {\npublic:\n    bool isScramble(string s1, string s2) {\n        return isScramble_2(s1, s2);\n    }\n    \n    // solution 1: dp.\n    bool isScramble_1(string s1, string s2) {\n        if(s1.size() != s2.size()) return false;\n        int N = s1.size();\n        bool dp[N+1][N][N];\n        for (int k = 1; k <= N; ++k)\n            for (int i = 0; i <= N-k; ++i)\n                for (int j = 0; j <= N-k; ++j)\n                {\n                    dp[k][i][j] = false;\n                    if (k == 1) \n                        dp[1][i][j] = (s1[i] == s2[j]);\n                    for (int p = 1; p < k && !dp[k][i][j]; ++p)\n                        if (dp[p][i][j] && dp[k-p][i+p][j+p] || dp[p][i][j+k-p] && dp[k-p][i+p][j])\n                            dp[k][i][j] = true;\n                }\n        return dp[N][0][0];\n    }\n\n    // solution 2: recursion + pruning.\n    typedef string::iterator Iterator;\n    \n    bool isScramble_2(string s1, string s2) {\n        if (s1.size() != s2.size()) return false;\n        return isScrambleRe(s1.begin(), s2.begin(), s1.size());\n    }\n\n    bool isScrambleRe(Iterator s1, Iterator s2, int len) {\n        if (!hasSameLetters(s1, s2, len)) return false;\n        if (len == 0 || len == 1) return true;\n        for (int i = 1; i < len; ++i)  // highlight\n            if (isScrambleRe(s1, s2, i) && isScrambleRe(s1 + i, s2 + i, len - i) ||\n                isScrambleRe(s1, s2 + len - i, i) && isScrambleRe(s1 + i, s2, len - i))\n                return true;\n        return false;\n    }\n\n    bool hasSameLetters(Iterator s1, Iterator s2, int len) {\n        int count[256] = {0};\n        for (int i = 0; i < len; ++i) count[*s1++]++;\n        for (int i = 0; i < len; ++i) count[*s2++]--;\n        for (int i = 0; i < 256; ++i)\n            if (count[i] != 0) return false;\n        return true;\n    }\n};\n"
  },
  {
    "path": "SearchInsertPosition.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 18, 2013\n Problem:    Search Insert Position\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_35\n Notes:\n Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.\n You may assume no duplicates in the array.\n Here are few examples.\n [1,3,5,6], 5 -> 2\n [1,3,5,6], 2 -> 1\n [1,3,5,6], 7 -> 4\n [1,3,5,6], 0 -> 0\n\n Solution: Binary search.\n */\n\nclass Solution {\npublic:\n    int searchInsert(int A[], int n, int target) {\n        int i = 0, j = n - 1;\n        while (i <= j)\n        {\n            int mid = (i + j) / 2;\n            if (A[mid] == target)\n                return mid;\n            if (A[mid] < target)\n                i = mid + 1;\n            else\n                j = mid - 1;\n        }\n        return i;\n    }\n};"
  },
  {
    "path": "Searcha2DMatrix.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 16, 2013\n Update:     Sep 27, 2013\n Problem:    Search a 2D Matrix\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_74\n Notes:\n Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:\n\n Integers in each row are sorted from left to right.\n The first integer of each row is greater than the last integer of the previous row.\n For example,\n\n Consider the following matrix:\n\n [\n    [1,   3,  5,  7],\n    [10, 11, 16, 20],\n    [23, 30, 34, 50]\n ]\n Given target = 3, return true.\n\n Solution: Binary-search.\n */\n\nclass Solution {\npublic:\n    bool searchMatrix(vector<vector<int> > &matrix, int target) {\n        return searchMatrix_2(matrix, target);\n    }\n    \n    // Solution 1.\n    bool searchMatrix_1(vector<vector<int> > &matrix, int target) {\n        if (matrix.empty() || matrix[0].empty()) return false;\n        int N = matrix.size(), M = matrix[0].size();\n        int i = 0, j = N-1;\n        while (i <= j)\n        {\n            int mid = (i + j) / 2;\n            if (matrix[mid][0] == target) return true;\n            else if (matrix[mid][0] < target) i++;\n            else j--;\n        }\n        int row = j;\n        if (row < 0) return false;\n        i = 0, j = M - 1;\n        while (i <= j)\n        {\n            int mid = (i + j) / 2;\n            if (matrix[row][mid] == target) return true;\n            else if (matrix[row][mid] < target) i++;\n            else j--;\n        }\n        return false;\n    }\n    \n    // Solution 2.\n    bool searchMatrix_2(vector<vector<int> > &matrix, int target) {\n        if (matrix.empty() || matrix[0].empty()) return false;\n        int N = matrix.size(), M = matrix[0].size();\n        int i = 0, j = M * N - 1;\n        while (i <= j)\n        {\n            int mid = (i + j) / 2;\n            int row = mid / M, col = mid % M;\n            if (matrix[row][col] == target) return true;\n            else if (matrix[row][col] < target) i = mid + 1;\n            else j = mid - 1;\n        }\n        return false;\n    }\n};"
  },
  {
    "path": "SearchforaRange.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 8, 2013\n Problem:    Search for a Range\n Difficulty: Medium\n Source:     http://leetcode.com/onlinejudge#question_34\n Notes:\n Given a sorted array of integers, find the starting and ending position of a given target value.\n\n Your algorithm's runtime complexity must be in the order of O(log n).\n\n If the target is not found in the array, return [-1, -1].\n\n For example,\n Given [5, 7, 7, 8, 8, 10] and target value 8,\n return [3, 4].\n\n Solution: It takes O(lgN) to find both the lower-bound and upper-bound.\n */\n\nclass Solution {\npublic:\n    vector<int> searchRange(int A[], int n, int target) {\n        vector<int> res(2, -1);\n        int lower = getLowerBound(A, n, target);\n        int upper = getUpperBound(A, n, target);\n        if (lower <= upper)\n        {\n            res[0] = lower;\n            res[1] = upper;\n        }\n        return res;\n    }\n    \n    int getLowerBound(int A[], int n, int target)\n    {\n        int l = 0, u = n-1;\n        while (l <= u)\n        {\n            int mid = (l + u) / 2;\n            if (A[mid] < target)\n                l = mid + 1;\n            else\n                u = mid - 1;\n        }\n        return l;\n    }\n    \n    int getUpperBound(int A[], int n, int target)\n    {\n        int l = 0, u = n-1;\n        while (l <= u)\n        {\n            int mid = (l + u) / 2;\n            if (A[mid] <= target)\n                l = mid + 1;\n            else\n                u = mid - 1;\n        }\n        return u;\n    }\n};\n"
  },
  {
    "path": "SearchinRotatedSortedArray.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 8, 2013\n Update:     Aug 7, 2013\n Problem:    Search in Rotated Sorted Array\n Difficulty: Medium\n Source:     http://leetcode.com/onlinejudge#question_33\n Notes:\n Suppose a sorted array is rotated at some pivot unknown to you beforehand.\n (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).\n You are given a target value to search. If found in the array return its index, otherwise return -1.\n You may assume no duplicate exists in the array.\n\n Solution: Binary search. O(lgn) eg. [4 5 6] -7- 8 1 2, 5 6 0 -1- [2 3 4]\n */\n\nclass Solution {\npublic:\n    int search(int A[], int n, int target) {\n        int i = 0, j = n - 1;\n        while (i <= j)\n        {\n            int mid = (i + j) / 2;\n            if (A[mid] == target)\n                return mid;\n            if (A[i] <= A[mid])\n            {\n                if (A[i] <= target && target < A[mid])\n                    j = mid - 1;\n                else\n                    i = mid + 1;\n            }\n            else\n            {\n                if (A[mid] < target && target <= A[j])\n                    i = mid + 1;\n                else\n                    j = mid - 1;\n            }\n        }\n        return -1;\n    }\n};\n"
  },
  {
    "path": "SearchinRotatedSortedArrayII.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com : King, higuige@gmail.com\n Date:       Apr 8, 2013\n Update:     Nov 18, 2014\n Problem:    Search in Rotated Sorted Array II\n Difficulty: Medium\n Source:     http://leetcode.com/onlinejudge#question_81\n Notes:\n Suppose a sorted array is rotated at some pivot unknown to you beforehand.\n (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).\n What if duplicates are allowed?\n Would this affect the run-time complexity? How and why?\n Write a function to determine if a given target is in the array.\n\n Solution: Sequence search. O(n)\n           Since there are duplicates, it's hard to decide which branch to go if binary-search is deployed.\n */\n\nclass Solution {\npublic:\n    bool search(int A[], int n, int target) {\n        for (int i = 0; i < n; i++)\n            if (A[i] == target)\n                return true;\n        return false;\n    }\n    bool search_2(int A[], int n, int target) {\n        if (A == NULL) return -1;\n        int left = 0, right = n - 1;\n        while (left <= right) {\n            int mid = (left + right) /2;\n            if (A[mid] == target) return true;\n            if (A[left] < A[mid]) {\n                if (A[left] <= target && target < A[mid]) {\n                    right = mid - 1;\n                } else {\n                    left = mid + 1;\n                }\n            } else if (A[left] > A[mid]) {\n               if (A[mid] < target && target <= A[right]) {\n                    left = mid + 1;\n                } else {\n                    right = mid - 1;\n                } \n            } else {\n                if (A[mid] == A[right]) {\n                    ++left, --right;\n                } else {\n                    left = mid + 1;\n                }\n            }\n        }\n        return false;\n    }\n};"
  },
  {
    "path": "SetMatrixZeroes.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       May 25, 2013\n Update:     Jul 23, 2013\n Problem:    Set Matrix Zeroes\n Difficulty: Medium\n Source:     http://leetcode.com/onlinejudge#question_73\n Notes:\n Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.\n Follow up:\n Did you use extra space?\n A straight forward solution using O(mn) space is probably a bad idea.\n A simple improvement uses O(m + n) space, but still not the best solution.\n Could you devise a constant space solution?\n\n Solution: Use first row and column as auxiliary spaces instead of newly allocating ones.\n*/\n\nclass Solution {\npublic:\n    void setZeroes(vector<vector<int>> &matrix) {\n        if (matrix.empty()) return;\n        int N = matrix.size(), M = matrix[0].size();\n        bool setFirstRowZero = false;\n        bool setFirstColZero = false;\n\n        for (int i = 0; i < N && !setFirstColZero; ++i)\n            setFirstColZero = (matrix[i][0] == 0);\n        for (int j = 0; j < M && !setFirstRowZero; ++j)\n            setFirstRowZero = (matrix[0][j] == 0);\n\n        for (int i = 1; i < N; ++i)\n            for (int j = 1; j < M; ++j)\n                if (matrix[i][j] == 0) {\n                    matrix[0][j] = 0;\n                    matrix[i][0] = 0;\n                }\n\n        for (int i = 1; i < N; ++i)\n            if (matrix[i][0] == 0)\n                for (int j = 1; j < M; ++j)\n                    matrix[i][j] = 0;\n\n        for (int j = 1; j < M; ++j)\n            if (matrix[0][j] == 0)\n                for (int i = 1; i < N; ++i)\n                    matrix[i][j] = 0;\n\n        if (setFirstRowZero)\n            for (int j = 0; j < M; ++j)\n                matrix[0][j] = 0;\n\n        if (setFirstColZero)\n            for (int i = 0; i < N; ++i)\n                matrix[i][0] = 0;\n    }\n};\n"
  },
  {
    "path": "SimplifyPath.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       May 13, 2013\n Update:     Aug 11, 2013\n Problem:    Simplify Path\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_71\n Notes:\n Given an absolute path for a file (Unix-style), simplify it.\n\n For example,\n path = \"/home/\", => \"/home\"\n path = \"/a/./b/../../c/\", => \"/c\"\n\n Corner Cases:\n Did you consider the case where path = \"/../\"?\n In this case, you should return \"/\".\n Another corner case is the path might contain multiple slashes '/' together, such as \"/home//foo/\".\n In this case, you should ignore redundant slashes and return \"/home/foo\".\n\n Solution: Add an additional '/' at the end of 'path' for simply detecting the end.\n */\n\nclass Solution {\npublic:\n    string simplifyPath(string path) {\n        string res;\n        path += \"/\";\n        size_t pos = path.find_first_of(\"/\"), last = 0;\n        while (pos != string::npos)\n        {\n            string s = path.substr(last, pos - last);\n            if (s == \"..\") \n            {\n                if (!res.empty())\n                    res.resize(res.find_last_of(\"/\"));\n            }\n            else if (!s.empty() && s != \".\")\n            {\n                res += \"/\";\n                res += s;\n            }\n            last = pos + 1;\n            pos = path.find_first_of(\"/\", last);\n        }\n        return res.empty() ? \"/\" : res;\n    }\n};\n"
  },
  {
    "path": "SingleNumber.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Oct 3, 2013\n Problem:    Single Number\n Difficulty: Easy\n Source:     http://oj.leetcode.com/problems/single-number/\n Notes:\n Given an array of integers, every element appears twice except for one. \n Find that single one.\n Your algorithm should have a linear runtime complexity. \n Could you implement it without using extra memory?\n\n Solution: XOR.\n*/\n\nclass Solution {\npublic:\n    int singleNumber(int A[], int n) {\n        if (n < 1) return 0;\n        for (int i = 1; i < n; ++i)\n            A[0] ^= A[i];\n        return A[0];\n    }\n};\n"
  },
  {
    "path": "SingleNumberII.h",
    "content": "/*\n Author:     King, higuige@gmail.com : Annie Kim, anniekim.pku@gmail.com\n Date:       Oct 5, 2013\n Update:     Oct 5, 2014\n Problem:    Single Number II\n Difficulty: Easy\n Source:     http://oj.leetcode.com/problems/single-number-ii/\n Notes:\n Given an array of integers, every element appears three times except for one. \n Find that single one.\n Your algorithm should have a linear runtime complexity. Could you implement it \n without using extra memory?\n\n Solution: 1. Count the number of each bit.\n        2. We can improve this based on the previous solution using three bitmask variables.\n        3. An excellent answer by @ranmocy in LeetCode Discuss:\n        https://oj.leetcode.com/discuss/857/constant-space-solution?show=2542#a2542\n*/\n\nclass Solution {\npublic:\n    int singleNumber(int A[], int n) {\n        int count[32]={0};\n        int res = 0;\n        for (int i = 0; i < 32; ++i) {\n            for (int j = 0; j < n; ++j) {\n                if ((A[j]>>i)&1) {\n                    ++count[i];\n                }\n            }\n            res|= ((count[i]%3)<<i);\n        }\n        return res;\n    }\n    int singleNumber_2(int A[], int n) {\n        int twice = 0;\n        int once = 0;\n        for (int i = 0; i < n; ++i) {\n            twice |= once & A[i];\n            once ^= A[i];\n            int notthree = ~ (twice & once);\n            twice = twice & notthree;\n            once  = once & notthree;\n        }\n        return once;\n    }\n    int singleNumber_3(int A[], int n) {\n        if (A == NULL) return 0;\n        int x0 = ~0, x1 = 0, x2 = 0, t;\n        for (int i = 0; i < n; ++i) {\n            t = x2;\n            x2 = (x1 & A[i]) | (x2 & ~A[i]);\n            x1 = (x0 & A[i]) | (x1 & ~A[i]);\n            x0 = (t & A[i]) | (x0 & ~A[i]);\n        }\n        return x1;\n    }\n};\n"
  },
  {
    "path": "SortColors.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 8, 2013\n Update:     Jul 24, 2013\n Problem:    Sort Colors\n Difficulty: Medium\n Source:     http://leetcode.com/onlinejudge#question_75\n Notes:\n Given an array with n objects colored red, white or blue, sort them so that objects of the same color\n are adjacent, with the colors in the order red, white and blue.\n Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.\n Note:\n You are not suppose to use the library's sort function for this problem.\n Follow up:\n A rather straight forward solution is a two-pass algorithm using counting sort.\n First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with \n total number of 0's, then 1's and followed by 2's.\n Could you come up with an one-pass algorithm using only constant space?\n\n Solution: 0 0 0 1 1 1 1 ...... 2 2 2 2\n               |         |      |\n             zero        i     two\n              ->        ->     <-  \n */\n\nclass Solution {\npublic:\n    void sortColors(int A[], int n) {\n        int zero = -1, two = n;\n        int i = 0;\n        while (i < two)\n        {\n            switch(A[i])\n            {\n            case 0:\n                swap(A[i++], A[++zero]);\n                break;\n            case 1:\n                i++;\n                break;\n            case 2:\n                swap(A[i], A[--two]);\n            }\n        }\n    }\n};\n"
  },
  {
    "path": "SortList.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Jan 8, 2014\n Problem:    Sort List\n Difficulty: Medium\n Source:     http://oj.leetcode.com/problems/sort-list/\n Notes:\n Sort a linked list in O(nlogn) time using constant space complexity.\n\n Solution: merge sort.\n */\n\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(int x) : val(x), next(NULL) {}\n * };\n */\n \nclass Solution {\npublic:\n    ListNode *sortList(ListNode *head) {\n        return sortLinkedList(head, getLength(head));\n    }\n    \n    ListNode* sortLinkedList(ListNode *&head, int N) {\n        if (N == 0) return NULL;\n        if (N == 1) {\n            ListNode* cur = head;\n            head = head->next;\n            cur->next = NULL;\n            return cur;\n        }\n        int half = N / 2;\n        ListNode* head1 = sortLinkedList(head, half);\n        ListNode* head2 = sortLinkedList(head, N - half);\n        return mergeList(head1, head2);\n    }\n    \n    ListNode* mergeList(ListNode *head1, ListNode*head2) {\n        ListNode dummy(0); dummy.next = NULL;\n        ListNode *cur = &dummy;\n        while (head1 && head2)\n        {\n            ListNode **min = head1->val < head2->val ? &head1 : &head2;\n            cur->next = *min;\n            cur = cur->next;\n            *min = (*min)->next;\n        }\n        if (!head1) cur->next = head2;\n        if (!head2) cur->next = head1;\n        return dummy.next;\n    }\n    \n    int getLength(ListNode *head) {\n        int length = 0;\n        while (head) {\n            length++;\n            head = head->next;\n        }\n        return length;\n    }\n};"
  },
  {
    "path": "SpiralMatrix.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       May 13, 2013\n Update:     Sep 30, 2013\n Problem:    Spiral Matrix\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_54\n Notes:\n Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.\n For example,\n Given the following matrix:\n [\n [ 1, 2, 3 ],\n [ 4, 5, 6 ],\n [ 7, 8, 9 ]\n ]\n You should return [1,2,3,6,9,8,7,4,5].\n\n Solution: ...\n */\n\nclass Solution {\npublic:\n    vector<int> spiralOrder(vector<vector<int> > &matrix) {\n        vector<int> res;\n        if (matrix.empty() || matrix[0].empty()) return res;\n        int imin = 0, imax = matrix.size()-1;\n        int jmin = 0, jmax = matrix[0].size()-1;\n        while (true)\n        {\n            for (int j = jmin; j <= jmax; ++j) res.push_back(matrix[imin][j]);\n            if (++imin > imax) break;\n            for (int i = imin; i <= imax; ++i) res.push_back(matrix[i][jmax]);\n            if (jmin > --jmax) break;\n            for (int j = jmax; j >= jmin; --j) res.push_back(matrix[imax][j]);\n            if (imin > --imax) break;\n            for (int i = imax; i >= imin; --i) res.push_back(matrix[i][jmin]);\n            if (++jmin > jmax) break;\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "SpiralMatrixII.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       May 13, 2013\n Update:     Aug 24, 2013\n Problem:    Spiral Matrix II\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_59\n Notes:\n Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.\n For example,\n Given n = 3,\n You should return the following matrix:\n [\n [ 1, 2, 3 ],\n [ 8, 9, 4 ],\n [ 7, 6, 5 ]\n ]\n\n Solution: ...\n */\n\nclass Solution {\npublic:\n    vector<vector<int> > generateMatrix(int n) {\n        if (n == 0) return vector<vector<int> >();\n        vector<vector<int> > res(n, vector<int>(n));\n        int imin = 0, imax = n-1, jmin = 0, jmax = n-1;\n        int number = 1;\n        while (true)\n        {\n            for (int j = jmin; j <= jmax; ++j) res[imin][j] = number++;\n            if (++imin > imax) break;\n            for (int i = imin; i <= imax; ++i) res[i][jmax] = number++;\n            if (jmin > --jmax) break;\n            for (int j = jmax; j >= jmin; --j) res[imax][j] = number++;\n            if (imin > --imax) break;\n            for (int i = imax; i >= imin; --i) res[i][jmin] = number++;\n            if (++jmin > jmax) break;\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "Sqrt(x).h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 18, 2013\n Problem:    Sqrt(x)\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_69\n Notes:\n Implement int sqrt(int x).\n Compute and return the square root of x.\n\n Solution: 1. Binary search in range [0, x / 2 + 1].\n           2. Newton iteration method. x(i+1) = (x(i) + n/x(i)) / 2.\n See my blog (http://www.cnblogs.com/AnnieKim/archive/2013/04/18/3028607.html) for more explanation (in Chinese).\n */\n\nclass Solution {\npublic:\n    int sqrt_1(int x) {\n        long long i = 0;\n        long long j = x / 2 + 1;\n        while (i <= j)\n        {\n            long long mid = (i + j) / 2;\n            long long sq = mid * mid;\n            if (sq == x) return mid;\n            else if (sq < x) i = mid + 1;\n            else j = mid - 1;\n        }\n        return j;\n    }\n\n    int sqrt_2(int x) {\n        if (x == 0) return 0;\n        double last = 0;\n        double res = 1;\n        while (res != last)\n        {\n            last = res;\n            res = (res + x / res) / 2;\n        }\n        return int(res);\n    }\n};\n"
  },
  {
    "path": "StringtoInteger(atoi).h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       May 17, 2013\n Update:     Dec 14, 2014(By wangjingui@outlook.com)\n Problem:    String to Integer (atoi)\n Difficulty: Easy\n Source:     https://oj.leetcode.com/problems/string-to-integer-atoi/solution/\n Notes:\n Implement atoi to convert a string to an integer.\n Hint: Carefully consider all possible input cases. If you want a challenge, please do not \n see below and ask yourself what are the possible input cases.\n Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). \n You are responsible to gather all the input requirements up front.\n\n Requirements for atoi:\n The function first discards as many whitespace characters as necessary until the first \n non-whitespace character is found. Then, starting from this character, takes an optional\n initial plus or minus sign followed by as many numerical digits as possible, and interprets \n them as a numerical value.\n The string can contain additional characters after those that form the integral number, which \n are ignored and have no effect on the behavior of this function.\n If the first sequence of non-whitespace characters in str is not a valid integral number, or \n if no such sequence exists because either str is empty or it contains only whitespace characters, \n no conversion is performed.\n If no valid conversion could be performed, a zero value is returned. If the correct value is out \n of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.\n\n Solution: 1. use long type to store the result to deal with overflow.\n           2. To deal with overflow, inspect the current number before multiplication. \n            If the current number is greater than 214748364, we know it is going to overflow.\n            On the other hand, if the current number is equal to 214748364, \n            we know that it will overflow only when the current digit is greater than or equal to 8..\n */\n\nclass Solution {\npublic:\n    int atoi_1(const char *str) {\n        if (!str) return 0;\n        while (*str == ' ') str++;\n        bool positive = true;\n        if (*str == '+' || *str == '-') {\n            positive = *str == '+';\n            str++;\n        }\n        long long res = 0;\n        while (isdigit(*str)) {\n            res = res * 10 + (*str - '0');\n            str++;\n        }\n        res = positive ? res : -res;\n        if (res > INT_MAX) return INT_MAX;\n        if (res < INT_MIN) return INT_MIN;\n        return (int)res;\n    }\n    int atoi_2(const char *str) {\n        if(str == NULL) return 0;\n        int res = 0;\n        bool sign = true;\n        while(*str == ' ') str++;\n        if(*str == '+' || *str == '-') {\n            sign = *str == '+';\n            str++;\n        }\n        while(isdigit(*str)) {\n            if(res > INT_MAX/10 || (res == INT_MAX / 10 && *str - '0' > INT_MAX % 10)){\n                return sign ? INT_MAX : INT_MIN;\n            }\n            res =  res * 10 + *str - '0';\n            str++;\n        }\n        return  sign ? res : -res;\n    }\n};\n"
  },
  {
    "path": "Subsets.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com : King, higuige@gmail.com\n Date:       Apr 24, 2013\n Update:     Nov 18, 2014\n Problem:    Subsets\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_78\n Notes:\n Given a set of distinct integers, S, return all possible subsets.\n Note:\n Elements in a subset must be in non-descending order.\n The solution set must not contain duplicate subsets.\n For example,\n If S = [1,2,3], a solution is:\n [\n  [3],\n  [1],\n  [2],\n  [1,2,3],\n  [1,3],\n  [2,3],\n  [1,2],\n  []\n ]\n\n Solution: 1. Recursive solution.\n           2. Iterative solution. Contributed by yinlinglin.\n           3. Updated Recursive solution.\n           4. Updated Iterative solution.\n */\n\nclass Solution {\npublic:\n    vector<vector<int> > subsets(vector<int> &S) {\n        return subsets_1(S);\n    }\n    \n    vector<vector<int> > subsets_1(vector<int> &S) {\n        vector<vector<int> > res(1, vector<int>());\n        sort(S.begin(), S.end());\n        vector<int> set;\n        int N = S.size();\n        for (int l = 1; l <= N; ++l)\n            subsetsRe(S, l, 0, set, res);\n        return res;\n    }\n    \n    void subsetsRe(vector<int> &S, int L, int start, vector<int> &set, vector<vector<int> > &res)\n    {\n        int N = S.size(), M = set.size();\n        if (M == L) {\n            res.push_back(set);\n            return;\n        }\n        for (int i = start; i <= N - (L - M); ++i) {\n            set.push_back(S[i]);\n            subsetsRe(S, L, i + 1, set, res);\n            set.pop_back();\n        }\n    }\n    \n    vector<vector<int> > subsets_2(vector<int> &S) {\n        vector<vector<int> > res(1, vector<int>());\n        sort(S.begin(), S.end());\n        int N = S.size();\n        for (int L = 1; L <= N; ++L)\n        {\n            int stk[L];\n            stk[0] = 0;\n            int top = 0;\n            while (true)\n            {\n                if (stk[top] == N)\n                {\n                    top--;\n                    if (top < 0) break;\n                    stk[top]++;\n                }\n                else if (top == L - 1) \n                {\n                    vector<int> set;\n                    for (int i = 0; i < L; ++i)\n                        set.push_back(S[stk[i]]);\n                    res.push_back(set);\n                    stk[top]++;\n                }\n                else\n                {\n                    top++;\n                    stk[top] = stk[top-1] + 1;\n                }\n            }\n        }\n        return res;\n    }\n\n    vector<vector<int> > subsets_3(vector<int> &S) {\n        int sz = S.size();\n        vector<vector<int>> res(1);\n        sort(S.begin(), S.end());\n        for (int i = 0; i < S.size(); ++i) {\n            int sz = res.size();\n            for (int j = 0; j < sz; ++j) {\n                res.push_back(res[j]);\n                res.back().push_back(S[i]);\n            }\n        }\n        return res;\n    }\n\n    vector<vector<int> > subsets_4(vector<int> &S) {\n        vector<vector<int>> res;\n        sort(S.begin(), S.end());\n        vector<int> path;\n        dfs(S,res,path,0);\n        return res;\n    }\n    void dfs(vector<int> &S, vector<vector<int>>& res, vector<int>&path, size_t step) {\n        res.push_back(path);\n        for (int i = step; i < S.size(); ++i) {\n            path.push_back(S[i]);\n            dfs(S,res,path,i+1);\n            path.pop_back();\n        }\n    }\n};\n"
  },
  {
    "path": "SubsetsII.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com : King, higuige@gmail.com\n Date:       Apr 30, 2013\n Update:     Nov 18, 2014\n Problem:    Subsets II\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_90\n Notes:\n Given a collection of integers that might contain duplicates, S, return all possible subsets.\n Note:\n Elements in a subset must be in non-descending order.\n The solution set must not contain duplicate subsets.\n For example,\n If S = [1,2,2], a solution is:\n [\n  [2],\n  [1],\n  [1,2,2],\n  [2,2],\n  [1,2],\n  []\n ]\n\n Solution: ..Similar to Subset I.\n */\nclass Solution {\npublic:\n    vector<vector<int> > subsetsWithDup(vector<int> &S) {\n        vector<vector<int>> res;\n        sort(S.begin(), S.end());\n        vector<int> path;\n        dfs(S,res,path,0);\n        return res;\n    }\n    void dfs(vector<int> &S, vector<vector<int>>& res, vector<int>&path, size_t step) {\n        res.push_back(path);\n        for (int i = step; i < S.size(); ++i) {\n            if(i!=step&&S[i]==S[i-1]) continue;\n            path.push_back(S[i]);\n            dfs(S,res,path,i+1);\n            path.pop_back();\n        }\n    }\n    // Solution 2. iterative solution.\n    vector<vector<int> > subsetsWithDup_2(vector<int> &S) {\n        vector<vector<int> > res(1);\n        sort(S.begin(),S.end());\n        size_t presz = 0;\n        for(int i=0;i<S.size();i++){\n            int sz = res.size();\n            for (int j = 0; j < sz; ++j) {\n                if(i==0||S[i]!=S[i-1]||j >= presz) {\n                    res.push_back(res[j]);\n                    res.back().push_back(S[i]);\n                }\n            }\n            presz = sz;\n        }\n        return res;\n    }\n};"
  },
  {
    "path": "SubstringwithConcatenationofAllWords.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com : Andy, nkuwjg@gmail.com\n Date:       May 26, 2013\n Update:     Jan 15, 2015\n Problem:    Substring with Concatenation of All Words\n Difficulty: Easy\n Source:     https://oj.leetcode.com/problems/substring-with-concatenation-of-all-words/\n Notes:\n You are given a string, S, and a list of words, L, that are all of the same length. Find all \n starting indices of substring(s) in S that is a concatenation of each word in L exactly once \n and without any intervening characters.\n For example, given:\n S: \"barfoothefoobarman\"\n L: [\"foo\", \"bar\"]\n You should return the indices: [0,9].\n (order does not matter).\n\n Solution: 1. Brute + HashMap.\n           2. Sliding Window + HashMap.\n*/\nclass Solution {\npublic:\n    vector<int> findSubstring_1(string S, vector<string> &L) {\n        vector<int> res;\n        if (S.empty() || L.empty()) return res;\n        int M = S.size(), N = L.size();\n        int K = L[0].size();\n        unordered_map<string, int> need;\n        unordered_map<string, int> found;\n        for (int i = 0; i < N; ++i)\n            need[L[i]]++;\n        for (int i = 0; i <= M - N * K; ++i)\n        {\n            found.clear();\n            int j;\n            for (j = 0; j < N; ++j)\n            {\n                string s = S.substr(i + j * K, K);\n                auto it = need.find(s);\n                if (it == need.end())\n                    break;\n                if (it->second <= found[s])\n                    break;\n                found[s]++;\n            }\n            if (j == N) res.push_back(i);\n        }\n        return res;\n    }\n    vector<int> findSubstring(string S, vector<string> &L) {\n        vector<int> res;\n        if (S.empty() || L.empty()) return res;\n        unordered_map<string, int> need;\n        for (int i = 0; i < L.size(); ++i)\n            need[L[i]]++;\n        int n = L[0].length(), m = L.size();\n        for (int i = 0; i < n; ++i) {\n            unordered_map<string, int> find;\n            for (int start = i, end = i, count = 0; end + n <= S.length(); end += n) {\n                string str = S.substr(end, n);\n                auto it = need.find(str);\n                if (it == need.end()) {\n                    start = end + n;\n                    find.clear();\n                    count = 0;\n                    continue;\n                }\n                while (find.find(str) != find.end() && find[str] >= need[str]) {\n                    string subStart = S.substr(start, n);\n                    find[subStart]--;\n                    start += n;\n                    --count;\n                }\n                find[str]++;\n                ++count;\n                if (count != m) continue;\n                res.push_back(start);\n            }\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "SudokuSolver.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Jun 19, 2013\n Update:     Sep 29, 2013\n Problem:    Sudoku Solver\n Difficulty: Medium\n Source:     http://leetcode.com/onlinejudge#question_37\n Notes:\n Write a program to solve a Sudoku puzzle by filling the empty cells.\n Empty cells are indicated by the character '.'.\n You may assume that there will be only one unique solution.\n\n Solution: back-tracking..\n */\n\nclass Solution {\npublic:\n    typedef vector<vector<char> > BOARDTYPE;\n    \n    void solveSudoku(BOARDTYPE &board) {\n        solveSudokuRe(board, 0, 0);\n    }\n    \n    bool solveSudokuRe(BOARDTYPE &board, int row, int col) {\n        getNextEmpty(board, row, col);\n        if (row == 9) return true;\n        vector<bool> avail(9, true);\n        getAvailable(board, avail, row, col);\n        for (int i = 0; i < 9; ++i)\n        {\n            if (!avail[i]) continue;\n            board[row][col] = i + '1';\n            if (solveSudokuRe(board, row, col)) return true;\n        }\n        board[row][col] = '.';\n        return false;\n    }\n    \n    void getNextEmpty(BOARDTYPE &board, int &row, int &col) {\n        do {\n            if (board[row][col] == '.') return;\n            row = (col == 8) ? row + 1 : row;\n            col = (col + 1) % 9;\n        } while (row < 9);\n    }\n    \n    void getAvailable(BOARDTYPE &board, vector<bool> &avail, int row, int col) {\n        for (int i = 0; i < 9; ++i) {\n            if (board[row][i] != '.') avail[board[row][i]-'1'] = false;\n            if (board[i][col] != '.') avail[board[i][col]-'1'] = false;\n            int box_i = row/3*3 + i/3, box_j = col/3*3 + i%3;\n            if (board[box_i][box_j] != '.') avail[board[box_i][box_j]-'1'] = false;\n        }\n    }\n};"
  },
  {
    "path": "SumRoottoLeafNumbers.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 23, 2013\n Update:     Jul 21, 2013\n Problem:    Sum Root to Leaf Numbers\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_129\n Notes:\n Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.\n An example is the root-to-leaf path 1->2->3 which represents the number 123.\n Find the total sum of all root-to-leaf numbers.\n For example,\n   1\n  / \\\n 2   3\n The root-to-leaf path 1->2 represents the number 12.\n The root-to-leaf path 1->3 represents the number 13.\n Return the sum = 12 + 13 = 25.\n\n Solution: 1. Recursion (add to sum when reaching the leaf).\n           2. Iterative solution.\n */\n\n/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    int sumNumbers(TreeNode *root) {\n        return sumNumbers_1(root);\n    }\n    \n    int sumNumbers_1(TreeNode *root) {\n        int sum = 0;\n        sumNumbersRe(root, 0, sum);\n        return sum;\n    }\n    \n    void sumNumbersRe(TreeNode *node, int num, int &sum) {\n        if (!node) return;\n        num = num * 10 + node->val;\n        if (!node->left && !node->right) { \n            sum += num;\n            return;\n        }\n        sumNumbersRe(node->left, num, sum);\n        sumNumbersRe(node->right, num, sum);\n    }\n    \n    int sumNumbers_2(TreeNode *root) {\n        if (!root) return 0;\n        int res = 0;\n        queue<pair<TreeNode *, int>> q;\n        q.push(make_pair(root, 0));\n        while(!q.empty())\n        {\n            TreeNode *node = q.front().first;\n            int sum = q.front().second * 10 + node->val;\n            q.pop();\n            if (!node->left && !node->right)\n            {\n                res += sum;\n                continue;\n            }\n            if (node->left)\n                q.push(make_pair(node->left, sum));\n            if (node->right)\n                q.push(make_pair(node->right, sum));\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "SurroundedRegions.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       May 20, 2013\n Update:     Aug 21, 2013\n Problem:    Surrounded Regions\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_130\n Notes:\n Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'.\n A region is captured by flipping all 'O's into 'X's in that surrounded region .\n For example,\n X X X X\n X O O X\n X X O X\n X O X X\n After running your function, the board should be:\n X X X X\n X X X X\n X X X X\n X O X X\n\n Solution: Traverse from the boarder to the inside and mark all the 'O's that are not surrounded by 'X' as 'V' (visited).\n           1. DFS.\n           2. BFS (queue).\n */\n\nclass Solution {\npublic:\n    typedef vector<vector<char> > BOARDTYPE;\n    \n    void solve(BOARDTYPE &board) {\n        if (board.empty() || board[0].empty()) return;\n        int N = board.size(), M = board[0].size();\n        for (int i = 0; i < N; ++i)\n            for (int j = 0; j < M; ++j)\n                if (i == 0 || j == 0 || i == N-1 || j == M-1)\n                    bfs(board, i, j); // you may call dfs or bfs here!\n        for (int i = 0; i < N; ++i)\n            for (int j = 0; j < M; ++j)\n                board[i][j] = (board[i][j] == 'V') ? 'O' : 'X';\n    }\n    \n    void dfs(BOARDTYPE &board, int row, int col) {\n        int N = board.size(), M = board[0].size();\n        if (row < 0 || row >= N || col < 0 || col >= M) return;\n        if (board[row][col] != 'O') return;\n        board[row][col] = 'V';\n        dfs(board, row+1, col);\n        dfs(board, row-1, col);\n        dfs(board, row, col+1);\n        dfs(board, row, col-1);\n    }\n\n    void bfs(BOARDTYPE &board, int row, int col) {\n        if (board[row][col] != 'O') return;\n        int N = board.size(), M = board[0].size();\n        queue<pair<int, int>> q;\n        q.push(make_pair(row, col));\n        while (!q.empty())\n        {\n            int i = q.front().first, j = q.front().second;\n            q.pop();\n            if (i < 0 || i >= N || j < 0 || j >= M) continue;\n            if (board[i][j] != 'O') continue;// important to recheck!\n            board[i][j] = 'V';\n            q.push(make_pair(i-1, j));\n            q.push(make_pair(i+1, j));\n            q.push(make_pair(i, j-1));\n            q.push(make_pair(i, j+1));\n        }\n    }\n};\n"
  },
  {
    "path": "SwapNodesinPairs.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 9, 2013\n Update:     Sep 3, 2013\n Problem:    Swap Nodes in Pairs\n Difficulty: Medium\n Source:     http://leetcode.com/onlinejudge#question_24\n Notes:\n Given a linked list, swap every two adjacent nodes and return its head.\n For example,\n Given 1->2->3->4, you should return the list as 2->1->4->3.\n Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.\n\n Solution: 1. Iterative solution with constant space.\n           2. Recursive solution with O(n) space (for practice).\n */\n\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(int x) : val(x), next(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    ListNode *swapPairs(ListNode *head) {\n        return swapPairs_1(head);\n    }\n    \n    ListNode *swapPairs_1(ListNode *head) {\n        ListNode dummy(0), *cur = &dummy;\n        cur->next = head;\n        while (cur->next && cur->next->next)\n        {\n            ListNode *move = cur->next->next;\n            cur->next->next = move->next;\n            move->next = cur->next;\n            cur->next = move;\n            cur = move->next;\n        }\n        return dummy.next;\n    }\n    \n    ListNode *swapPairs_2(ListNode *head) {\n        if (!head || !head->next) return head;\n        ListNode *first = head, *second = head->next;\n        first->next = second->next;\n        second->next = first;\n        first->next = swapPairs(first->next);\n        return second;\n    }\n};\n"
  },
  {
    "path": "SymmetricTree.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com : King, higuige@gmail.com\n Date:       Apr 22, 2013\n Update:     Oct 07, 2014\n Problem:    Symmetric Tree\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_101\n Notes:\n Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).\n For example, this binary tree is symmetric:\n     1\n    / \\\n   2   2\n  / \\ / \\\n 3  4 4  3\n But the following is not:\n    1\n   / \\\n  2   2\n   \\   \\\n   3    3\n Note:\n Bonus points if you could solve it both recursively and iteratively.\n\n Solution: 1. Recursive solution 2.Iterative way (queue).\n */\n/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    bool isSymmetric(TreeNode *root) {\n        return isSymmetric_2(root);\n    }\n    bool isSymmetric_1(TreeNode *root) {\n        if (root == NULL) return true;\n        return solve (root->left, root->right);\n    }\n    bool solve(TreeNode * t1, TreeNode * t2) {\n        if (!t1 && !t2) return true;\n        if (!t1 && t2 || t1 && !t2 || t1->val != t2->val) return false;\n        return solve(t1->left, t2->right) && solve(t1->right, t2->left);\n    }\n    bool isSymmetric_2(TreeNode *root) {\n        if (root == NULL) return true;\n        stack<TreeNode *> s;\n        s.push(root->left);\n        s.push(root->right);\n        while (!s.empty()) {\n            TreeNode *t2 = s.top(); s.pop();\n            TreeNode *t1 = s.top(); s.pop();\n            if (!t1 && !t2) continue;\n            if (!t1 && t2 || t1 && !t2 || t1->val != t2->val) return false;\n            s.push(t1->right);\n            s.push(t2->left);\n            s.push(t1->left);\n            s.push(t2->right);\n        }\n        return true;\n    }\n    bool isSymmetric_3(TreeNode *root) {\n        if (root == NULL) return true;\n        queue<TreeNode *> q;\n        q.push(root->left);\n        q.push(root->right);\n        while (!s.empty()) {\n            TreeNode *t2 = q.front(); q.pop();\n            TreeNode *t1 = q.front(); q.pop();\n            if (!t1 && !t2) continue;\n            if (!t1 && t2 || t1 && !t2 || t1->val != t2->val) return false;\n            q.push(t1->left);\n            q.push(t2->right);\n            q.push(t1->right);\n            q.push(t2->left);\n        }\n        return true;\n    }\n};"
  },
  {
    "path": "TextJustification.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       May 8, 2013\n Problem:    Text Justification\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_68\n Notes:\n Given an array of words and a length L, format the text such that each line has exactly L \n characters and is fully (left and right) justified.\n You should pack your words in a greedy approach; that is, pack as many words as you can in each line. \n Pad extra spaces ' ' when necessary so that each line has exactly L characters.\n Extra spaces between words should be distributed as evenly as possible. If the number of spaces \n on a line do not divide evenly between words, the empty slots on the left will be assigned more \n spaces than the slots on the right.\n For the last line of text, it should be left justified and no extra space is inserted between words.\n\n For example,\n words: [\"This\", \"is\", \"an\", \"example\", \"of\", \"text\", \"justification.\"]\n L: 16.\n Return the formatted lines as:\n [\n \"This    is    an\",\n \"example  of text\",\n \"justification.  \"\n ]\n Note: Each word is guaranteed not to exceed L in length.\n Corner Cases:\n A line other than the last line might contain only one word. What should you do in this case?\n In this case, that line should be left-justified.\n\n Solution: ...\n */\n\nclass Solution {\npublic:\n    vector<string> fullJustify(vector<string> &words, int L) {\n        vector<string> res;\n        int i = 0, N = words.size();\n        while (i < N)\n        {\n            int length = words[i].size();\n            int j = i + 1;\n            while (j < N && length + words[j].size() + (j-i) <= L)\n                length += words[j++].size();\n            // build line\n            string s(words[i]);\n            bool isLastLine = (j == N);\n            bool oneWord = (j == i + 1);\n            int average = isLastLine || oneWord ? 1 : (L - length) / (j - i - 1);\n            int extra = isLastLine || oneWord ? 0 : (L - length) % (j - i - 1);\n            for (int k = i + 1; k < j; ++k) {\n                s.append(extra > 0 ? average + 1 : average, ' ');\n                s.append(words[k]);\n                extra--;\n            }\n            s.append(L - s.size(), ' ');\n            // push line\n            res.push_back(s);\n            i = j;\n        }\n        return res;\n    }\n};"
  },
  {
    "path": "TrappingRainWater.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com : King, higuige@gmail.com\n Date:       May 25, 2013\n Update:     Oct 07, 2014\n Problem:    Trapping Rain Water\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_42\n Notes:\n Given n non-negative integers representing an elevation map where the width of \n each bar is 1, compute how much water it is able to trap after raining.\n For example, \n Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.\n\n Solution: 1. Find left bound and right bound for each element. O(n).\n           2. more space efficiency. Time: O(n), Space: O(1);\n*/\n\nclass Solution {\npublic:\n    int trap_1(int A[], int n) {\n        if (n == 0) return 0;\n        vector<int> maxLeft(n,0);\n        vector<int> maxRight(n,0);\n        maxLeft[0] = A[0];\n        maxRight[n - 1] = A[n - 1];\n        for (int i = 1; i < n; ++i) {\n            maxLeft[i] = max(maxLeft[i - 1], A[i]);\n            maxRight[n - 1 - i] = max(maxRight[n - i], A[n - 1 - i]);\n        }\n        \n        int res = 0;\n        for (int i = 1; i < n; ++i) {\n            res += min(maxLeft[i], maxRight[i]) - A[i];\n        }\n        return res;\n    }\n    int trap_2(int A[], int n) {\n        if (A == NULL || n <= 2) return 0;\n        int left= 1;\n        int right = n - 2;\n        int maxLeft = A[0];\n        int maxRight = A[n - 1];\n        int res = 0;\n        while (left <= right) {\n            if (maxLeft <= maxRight) {\n                res += max(0, maxLeft - A[left]);\n                maxLeft = max(maxLeft, A[left]);\n                ++left;\n            } else {\n                res += max(0, maxRight - A[right]);\n                maxRight = max(maxRight, A[right]);\n                --right;\n            }\n        }\n        return res;\n    }\n    int trap_3(int A[], int n) {\n        int i = 0, j = n - 1, res = 0, cur;\n        while (i < j) {\n            if (A[i] < A[j]) {\n                cur = i+1;\n                while (cur <= j && A[cur] <= A[i]) res += A[i] - A[cur++];\n                i = cur;\n            } else {\n                cur = j - 1;\n                while (cur >= i && A[cur] <= A[j]) res += A[j] - A[cur--];\n                j = cur;\n            }\n        }\n        return res;\n    }\n};"
  },
  {
    "path": "Triangle.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       May 14, 2013\n Problem:    Triangle\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_120\n Notes:\n Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.\n For example, given the following triangle\n [\n    [2],\n   [3,4],\n  [6,5,7],\n [4,1,8,3]\n ]\n The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).\n Note:\n Bonus point if you are able to do this using only O(n) extra space, where n is the total number \n of rows in the triangle.\n\n Solution: Note that there are n elements in the n-th row (n starts from 1).\n           1. DFS. (Time Limit Exceeded for large test data).\n           2. DP. Do not need additional spaces (happen in-place).\n           3. DP. O(n) space (If the input 'triangle' can not be changed).\n */\n\nclass Solution {\npublic:\n    int minimumTotal(vector<vector<int>> &triangle) {\n        return minimumTotal_2(triangle);\n    }\n\n    int minimumTotal_1(vector<vector<int>> &triangle) {\n        int res = INT_MAX;\n        minimumTotal_1_Re(triangle, 0, res, 0, 0);\n        return res;\n    }\n\n    void minimumTotal_1_Re(vector<vector<int>> &triangle, int partSum, int &res, int deep, int j)\n    {\n        if (deep == triangle.size()) {\n            res = min(res, partSum);\n            return;\n        }\n        for (int i = j; i < triangle[deep].size() && i <= j + 1; ++i)\n            minimumTotal_1_Re(triangle, partSum + triangle[deep][i], res, deep + 1, i);\n    }\n\n    int minimumTotal_2(vector<vector<int>> &triangle) {\n        for (int i = triangle.size() - 2; i >= 0; --i)\n            for (int j = 0; j < i + 1; ++j)\n                triangle[i][j] = triangle[i][j] + min(triangle[i+1][j], triangle[i+1][j+1]);\n        return triangle[0][0];\n    }\n\n    int minimumTotal_3(vector<vector<int>> &triangle) {\n        int N = triangle.size();\n        int *dp = new int[N];\n        for (int i = 0; i < N; ++i)\n            dp[i] = triangle[N-1][i];\n        for (int i = N - 2; i >= 0; --i)\n            for (int j = 0; j < i + 1; ++j)\n                dp[j] = triangle[i][j] + min(dp[j], dp[j+1]);\n        int res = dp[0];\n        delete [] dp;\n        return res;\n    }\n};"
  },
  {
    "path": "TwoSum.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Jan 17, 2013\n Update:     Jan 16, 2014\n Problem:    Two Sum\n Difficulty: Medium\n Source:     http://oj.leetcode.com/problems/two-sum/\n Notes:\n Given an array of integers, find two numbers such that they add up to a specific target number.\n\n The function twoSum should return indices of the two numbers such that they add up to the target, \n where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.\n\n You may assume that each input would have exactly one solution.\n\n Input: numbers={2, 7, 11, 15}, target=9\n Output: index1=1, index2=2\n\n Solution: 1. Sort first. O(nlgn)\n           2. Hash table. O(n)\n           \n Note:  Hash Table solution has been updated.  In case that the two elements are the same, \n        all the indices should be stored in the map.\n */\n\nbool compare(pair<int, int> a, pair<int, int> b) {\n    return a.first < b.first;\n}\n\nclass Solution {\npublic:\n    vector<int> twoSum(vector<int> &numbers, int target) {\n        return twoSum_1(numbers, target);\n    }\n    \n    vector<int> twoSum_1(vector<int> &numbers, int target) {\n        vector<pair<int, int>> nums(numbers.size());\n        for (int i = 0; i < numbers.size(); ++i)\n            nums[i] = make_pair(numbers[i], i+1);\n        sort(nums.begin(), nums.end(), compare);\n        \n        int l = 0, r = nums.size() - 1;\n        while (l < r)\n        {\n            int sum = nums[l].first + nums[r].first;\n            if (sum == target) break;\n            else if (sum < target) l++;\n            else r--;\n        }\n\n        vector<int> res;\n        res.push_back(min(nums[l].second, nums[r].second));\n        res.push_back(max(nums[l].second, nums[r].second));\n        return res;\n    }\n    \n    vector<int> twoSum_2(vector<int> &numbers, int target) {\n        unordered_map<int, int>  hash;\n        for (int i = 0; i < numbers.size(); ++i) {\n            int second = target - numbers[i];\n            if (hash.find(second) != hash.end()) {\n                return vector<int>{hash[res]+1, i+1};\n            } else {\n                hash.insert(pair<int, int>{numbers[i],i});\n            }\n        }\n        return vector<int>();\n    }\n};\n"
  },
  {
    "path": "TwoSumIII.h",
    "content": "/*\n Author:     King, wangjingui@outlook.com\n Date:       Dec 26, 2014\n Problem:    Two Sum III - Data structure design \n Difficulty: Easy\n Source:     https://oj.leetcode.com/problems/\n Notes:\n Design and implement a TwoSum class. \n It should support the following operations: add and find.\n add - Add the number to an internal data structure.\n find - Find if there exists any pair of numbers which sum is equal to the value.\n For example\n add(1); add(3); add(5);find(4) -> true; find(7) -> false,\n Solution: Thanks to Javaman Cao.\n */\n\nclass TwoSum {\npublic:\n    unordered_map<int,int> hash;\n    void add(int number) {\n        ++hash[number];\n    }\n    bool find(int value) {\n        for (unordered_map<int,int>::iterator t = hash.begin(); t != hash.end(); ++t) {\n            int x = value - t->first;\n            if (x <= t->first) {\n                unordered_map<int,int>::iterator it = hash.find(x); \n                if ((it != hash.end()) && ((t != it)  || (it->second > 1))) {\n                    return true;\n                }\n            }\n        }\n        return false;\n    }\n};"
  },
  {
    "path": "UniqueBinarySearchTrees.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com : King, higuige@gmail.com\n Date:       Jul 10, 2013\n Update:     Oct 07, 2014\n Problem:    Unique Binary Search Trees\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_96\n Notes:\n Given n, how many structurally unique BST's (binary search trees) that store values 1...n?\n For example,\n Given n = 3, there are a total of 5 unique BST's.\n 1         3     3      2      1\n  \\       /     /      / \\      \\\n   3     2     1      1   3      2\n  /     /       \\                 \\\n 2     1         2                 3\n\n Solution: dp.\n*/\n\nclass Solution {\npublic:\n    int numTrees(int n) {\n        return numTrees_2(n);\n    }\n    int numTrees_1(int n) {\n        int dp[n+1];\n        memset(dp, 0, sizeof(dp));\n        dp[0] = 1;\n        for (int i = 1; i <= n; ++i)\n            for (int j = 0; j < i; j++)\n                dp[i] += dp[j] * dp[i-j-1];\n        return dp[n];\n    }\n    int numTrees_2(int n) {\n        if (n < 0) return 0;\n        vector<int> dp(n+1, 0);\n        dp[0] = 1; dp[1] = 1;\n        for(int i = 2;i <= n; ++i){\n            dp[i] = dp[i-1] * (4 * i - 2)/(i + 1);\n        }\n        return dp[n];        \n    }\n};\n"
  },
  {
    "path": "UniqueBinarySearchTreesII.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Jul 11, 2013\n Problem:    Unique Binary Search Trees II\n Difficulty: Medium\n Source:     http://leetcode.com/onlinejudge#question_95\n Notes:\n Given n, generate all structurally unique BST's (binary search trees) that store values 1...n.\n For example,\n Given n = 3, your program should return all 5 unique BST's shown below.\n 1         3     3      2      1\n  \\       /     /      / \\      \\\n   3     2     1      1   3      2\n  /     /       \\                 \\\n 2     1         2                 3\n\n Solution: 1. DFS directly. (from the Internet)\n           2. DP + DFS. (my solution)\n              a. Generate trees for 'n' from 1 to n. (DP)\n              b. When generate trees for n = i, get the left and right subtrees \n                 by copying tree structures of dp[1...i-1]. (copy tree uses DFS)\n*/\n\nclass Solution {\npublic:\n    vector<TreeNode *> generateTrees(int n) {\n        return generateTrees_1(n);\n    }\n\n    // solution 1\n    vector<TreeNode *> generateTrees_1(int n) {\n        return generateTreesRe(1, n);\n    }\n\n    vector<TreeNode*> generateTreesRe(int l, int r) {\n        vector<TreeNode*> res;\n        if (l > r) {\n            res.push_back(NULL);\n            return res;\n        }\n        for (int k = l; k <= r; k++) {\n            vector<TreeNode*> leftTrees = generateTreesRe(l, k-1);\n            vector<TreeNode*> rightTrees = generateTreesRe(k+1, r);\n            for (size_t i = 0; i < leftTrees.size(); i++) {\n                for (size_t j = 0; j < rightTrees.size(); j++) {\n                    TreeNode* root = new TreeNode(k);\n                    root->left = leftTrees[i];\n                    root->right = rightTrees[j];\n                    res.push_back(root);\n                }\n            }\n        }\n        return res;\n    }\n\n    // solution 2\n    vector<TreeNode *> generateTrees_2(int n) {\n        vector<TreeNode *> dp[n+1];\n        dp[0] = vector<TreeNode *>(1, (TreeNode *)NULL);\n        for (int i = 1; i <= n; ++i)\n        {\n            for (int j = 1; j <= i; ++j)\n            {\n                for (int m = 0; m < dp[j-1].size(); ++m)\n                {\n                    for (int k = 0; k < dp[i-j].size(); ++k)\n                    {\n                        TreeNode *root = new TreeNode(j);\n                        CopyTree(dp[j-1][m], root->left, 0);\n                        CopyTree(dp[i-j][k], root->right, j);\n                        dp[i].push_back(root);\n                    }\n                }\n            }\n        }\n        return dp[n];\n    }\n\n    void CopyTree(TreeNode *original, TreeNode *&newNode, int diff)\n    {\n        if (!original) return;\n        newNode = new TreeNode(original->val + diff);\n        CopyTree(original->left, newNode->left, diff);\n        CopyTree(original->right, newNode->right, diff);\n    }\n};\n"
  },
  {
    "path": "UniquePaths.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com : King, higuige@gmail.com\n Date:       Apr 8, 2013\n Update:     Oct 9, 2014\n Problem:    Unique Paths\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_62\n Notes:\n A robot is located at the top-left corner of a m x n grid.\n The robot can only move either down or right at any point in time. The robot is trying to reach \n the bottom-right corner of the grid (marked 'Finish' in the diagram below).\n How many possible unique paths are there?\n\n Solution: \n 1. Use formula C(x,t) = t!/(x!*(t-x)!) (x should be large for calculation).\n 2. Dynamic programming. UP(i,j) = UP(i-1,j) + UP(i,j-1).\n */\n\nclass Solution {\npublic:\n    int uniquePaths_1(int m, int n) {\n        if (m == 1  || n == 1) return 1;\n        int t = (m-1)+(n-1);\n        int x = (m > n) ? (m-1) : (n-1);\n        \n        long long res = 1;\n        for (int i = t; i > x; i--)\n            res *= i;\n        for (int i = t-x; i > 1; i--)\n            res /= i;\n        \n        return res;\n    }\n\n    int uniquePaths_2(int m, int n) {\n        int dp[m][n];\n        for (int i = 0; i < m; i++)\n            dp[i][0] = 1;\n        for (int j = 0; j < n; j++)\n            dp[0][j] = 1;\n        \n        for (int i = 1; i < m; i++)\n            for (int j = 1; j < n; j++)\n                dp[i][j] = dp[i-1][j] + dp[i][j-1];\n        \n        return dp[m-1][n-1];\n    }\n    int uniquePaths_3(int m, int n) {\n        vector<int> dp(n, 1);\n        for (int i = 1; i < m; ++i) {\n            for (int j = 1; j < n; ++j) {\n                dp[j] += dp[j-1];    \n            }\n        }\n        return dp[n-1];\n};\n"
  },
  {
    "path": "UniquePathsII.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com : King, higuige@gmail.com\n Date:       Apr 9, 2013\n Update:     Oct 9, 2014\n Problem:    Unique Paths II\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_63\n Notes:\n Follow up for \"Unique Paths\":\n Now consider if some obstacles are added to the grids. How many unique paths would there be?\n An obstacle and empty space is marked as 1 and 0 respectively in the grid.\n For example,\n There is one obstacle in the middle of a 3x3 grid as illustrated below.\n [\n  [0,0,0],\n  [0,1,0],\n  [0,0,0]\n ]\n The total number of unique paths is 2.\n Note: m and n will be at most 100.\n\n Solution: Dynamic programming.\n */\n\nclass Solution {\npublic:\n    int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {\n        int m = obstacleGrid.size();\n        int n = obstacleGrid[0].size();\n        int dp[m][n];\n        if (obstacleGrid[0][0] == 1) return 0;\n        dp[0][0] = 1;\n        for (int i = 1; i < m; i++)\n            dp[i][0] = obstacleGrid[i][0] == 1 ? 0 : dp[i-1][0];\n        for (int j = 1; j < n; j++)\n            dp[0][j] = obstacleGrid[0][j] == 1 ? 0 : dp[0][j-1];\n        \n        for (int i = 1; i < m; i++)\n            for (int j = 1; j < n; j++)\n                dp[i][j] = obstacleGrid[i][j] == 1 ? 0: dp[i-1][j] + dp[i][j-1];\n        \n        return dp[m-1][n-1];\n    }\n    int uniquePathsWithObstacles_2(vector<vector<int> > &obstacleGrid) {\n        int m = obstacleGrid.size();\n        if (m == 0) return 0;\n        int n = obstacleGrid[0].size();\n        vector<int> dp(n+1,0);\n        if(obstacleGrid[0][0] || obstacleGrid[m-1][n-1]) return 0;\n        dp[1] = 1;\n        for (int i = 1; i <= m; ++i) {\n            dp[1] = obstacleGrid[i-1][0] ? 0 : dp[1];\n            for(int j = 2; j <= n; ++j) {\n                 dp[j] = obstacleGrid[i - 1][j - 1] == 1 ? 0: dp[j] + dp[j-1];\n            }\n        }\n        return dp[n];\n    }\n};\n"
  },
  {
    "path": "ValidNumber.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com : Andy, nkuwjg@gmail.com\n Date:       May 25, 2013\n Update:     Feb 7, 2015\n Problem:    Valid Number\n Difficulty: Hard\n Source:     https://oj.leetcode.com/problems/valid-number/\n Notes:\n Validate if a given string is numeric.\n Some examples:\n \"0\" => true\n \" 0.1 \" => true\n \"abc\" => false\n \"1 a\" => false\n \"2e10\" => true\n Note: It is intended for the problem statement to be ambiguous. You should gather all \n requirements up front before implementing one.\n\n Solution: This finite-state machine solution. Learn from fuwutu & snakeDling.\n*/\n\nclass Solution {\npublic:\n    bool isNumber_1(const char *s) {\n        enum InputType {INVALID, SPACE, SIGN, DIGIT, DOT, EXPONENT};\n        int transitionTable[][SPACEEND] = \n        { /* 0   1   2   3   4   5  */\n             0,  1,  2,  3,  4,  0, // 0: INVALID\n             0,  1,  2,  3,  4,  0, // 1: SPACE\n             0,  0,  0,  3,  4,  0, // 2: SIGN\n             0,  6,  0,  3,  7,  5, // 3: DIGIT\n             0,  0,  0,  7,  0,  0, // 4: DOT\n             0,  0,  2,  8,  0,  0, // 5: EXPONENT\n             0,  6,  0,  0,  0,  0, // 6: END WITH SPACE\n             0,  6,  0,  7,  0,  5, // 7: DOT AND DIGIT\n             0,  6,  0,  8,  0,  0, // 8: END WITH SPACE OR DIGIT\n        };\n        \n        InputType last = INVALID;\n        while (*s != '\\0')\n        {\n            InputType state = INVALID;\n            if (*s == ' ')\n                state = SPACE;\n            else if (isdigit(*s))\n                state = DIGIT;\n            else if (*s == '+' || *s == '-')\n                state = SIGN;\n            else if (*s == 'e')\n                state = EXPONENT;\n            else if (*s == '.')\n                state = DOT;\n            last = (InputType) transitionTable[last][state];\n            if (last == INVALID) return false;\n            s++;\n        }\n        bool validFinal[] = {0, 0, 0, 1, 0, 0, 1, 1, 1};\n        return validFinal[last];\n    }\n    bool isNumber_2(const char *s) {\n        bool dot = false, digit = false, exp = false;\n        while (*s  == ' ') ++s;\n        if (*s == '-' || *s == '+') ++s;\n        if (*s == 0) return false;\n        for (;*s != '\\0' && *s != ' '; ++s) {\n            if (isdigit(*s)) digit = true;\n            else if (*s == 'e' || *s == 'E') {\n                if (exp == true || digit == false || *(s+1) ==' ' || *(s+1) =='\\0') return false;\n                exp = true;\n            } else if (*s == '.') {\n                if (dot == true || exp == true) return false; \n                if (digit == false && (*(s+1) ==' ' || *(s+1) =='\\0')) return false;\n                dot = true;\n            } else if (*s == '-' || *s == '+') {\n                if (*(s+1) == ' ' || *(s+1) == '\\0') return false;\n                if (*(s-1) != 'e' && *(s-1) != 'E') return false;\n            } else return false;\n        }\n        while (*s  == ' ') ++s;\n        return *s == '\\0';\n    }\n};"
  },
  {
    "path": "ValidPalindrome.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 29, 2013\n Update:     Jul 19, 2013\n Problem:    Valid Palindrome\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_125\n Notes:\n Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.\n For example,\n \"A man, a plan, a canal: Panama\" is a palindrome.\n \"race a car\" is not a palindrome.\n Note:\n Have you consider that the string might be empty? This is a good question to ask during an interview.\n For the purpose of this problem, we define empty string as valid palindrome.\n\n Solution: traverse from both side.\n */\n#include <cctype> // needed for isalnum(), isupper() and tolower().\n\nclass Solution {\npublic:\n    bool isPalindrome(string s) {\n        for (int i = 0, j = s.size() - 1; i < j; ++i, --j)\n        {\n            while (i < j && !isalnum(s[i])) i++;\n            while (i < j && !isalnum(s[j])) j--;\n\n            if (tolower(s[i]) != tolower(s[j]))\n                return false;\n        }\n        return true;\n    }\n};\n"
  },
  {
    "path": "ValidParentheses.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 29, 2013\n Update:     Jul 14, 2013\n Problem:    Valid Parentheses\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_20\n Notes:\n Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.\n The brackets must close in the correct order, \"()\" and \"()[]{}\" are all valid but \"(]\" and \"([)]\" are not.\n\n Solution: stack.\n */\n\nclass Solution {\npublic:\n    bool isValid(string s) {\n        stack<char> stk;\n        for (int i = 0; i < s.size(); ++i)\n        {\n            if (s[i] == '(' || s[i] == '[' || s[i] == '{')\n            {\n                stk.push(s[i]);\n            }\n            else\n            {\n                if (stk.empty() || abs(stk.top() - s[i]) > 2) \n                    return false;\n                stk.pop();\n            }\n        }\n        return stk.empty();\n    }\n};\n"
  },
  {
    "path": "ValidSudoku.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       May 20, 2013\n Problem:    Valid Sudoku\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_36\n Notes:\n Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules (http://sudoku.com.au/TheRules.aspx).\n The Sudoku board could be partially filled, where empty cells are filled with the character '.'.\n\n Solution: 1. Traverse the Sudoku only once.\n           2. Bit manipulation. Use only one bit to represent a number. Space: sizeof(int) * (1+9+9).\n */\n\nclass Solution {\npublic:\n    bool isValidSudoku(vector<vector<char>> &board) {\n        const int N = 9;\n        int row, col[N] = {0}, box[N] = {0};\n        for (int i = 0; i < N; ++i)\n        {\n            row = 0;\n            for (int j = 0; j < N; ++j)\n            {\n                if (board[i][j] == '.') continue;\n                \n                int bit = 1 << (board[i][j] - '1');\n                int box_index = i/3*3 + j/3;\n                \n                if (row & bit || col[j] & bit || box[box_index] & bit)\n                    return false;\n                \n                row |= bit;\n                col[j] |= bit;\n                box[box_index] |= bit;\n            }\n        }\n        return true;\n    }\n};\n"
  },
  {
    "path": "ValidateBinarySearchTree.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 10, 2013\n Update:     Dec 25, 2014\n Problem:    Validate Binary Search Tree\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_98\n Notes:\n Given a binary tree, determine if it is a valid binary search tree (BST).\n Assume a BST is defined as follows:\n The left subtree of a node contains only nodes with keys less than the node's key.\n The right subtree of a node contains only nodes with keys greater than the node's key.\n Both the left and right subtrees must also be binary search trees.\n\n Solution: Recursion. 1. Add lower & upper bound. O(n)\n                      2. Inorder traversal with one additional parameter (value of predecessor). O(n)\n */\n\n/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    bool isValidBST(TreeNode *root) {\n        return isValidBST_1(root);\n    }\n\n    // solution 1: lower bound + higher bound\n    bool isValidBST_1(TreeNode *root) {\n        return isValidBSTRe_1(root, INT_MIN, INT_MAX);\n    }\n\n    bool isValidBSTRe_1(TreeNode *node, int lower, int upper){\n        if (!node) return true;\n        if (node->val <= lower || node->val >= upper) return false;\n\n        return isValidBSTRe_1(node->left, lower, node->val) && \n               isValidBSTRe_1(node->right, node->val, upper);\n    }\n\n    // solution 2: inorder\n    bool isValidBST_2(TreeNode *root) {\n        TreeNode * prev = NULL;\n        return inorder(root, prev);\n    }\n    bool inorder(TreeNode * root, TreeNode*&prev) {\n        if (root == NULL) return true;\n        if (inorder(root->left, prev) == false) \n            return false;\n        if (prev && root->val <= prev->val) return false;\n        prev = root;\n        return inorder(root->right,prev);\n    }\n};\n"
  },
  {
    "path": "WildcardMatching.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Aug 20, 2013\n Problem:    Wildcard Matching\n Difficulty: Medium\n Source:     https://oj.leetcode.com/problems/wildcard-matching/\n Notes:\n Implement wildcard pattern matching with support for '?' and '*'.\n '?' Matches any single character.\n '*' Matches any sequence of characters (including the empty sequence).\n The matching should cover the entire input string (not partial).\n The function prototype should be:\n bool isMatch(const char *s, const char *p)\n Some examples:\n isMatch(\"aa\",\"a\") ? false\n isMatch(\"aa\",\"aa\") ? true\n isMatch(\"aaa\",\"aa\") ? false\n isMatch(\"aa\", \"*\") ? true\n isMatch(\"aa\", \"a*\") ? true\n isMatch(\"ab\", \"?*\") ? true\n isMatch(\"aab\", \"c*a*b\") ? false\n\n Solution: ...\n*/\n\nclass Solution {\npublic:\n    bool isMatch(const char *s, const char *p) {\n        const char *sBackup = NULL, *pBackup = NULL;\n        while (*s != '\\0') {\n            if (*p == '*') {\n                while (*p == '*') ++p;\n                if (*p == '\\0') return true;\n                sBackup = s;\n                pBackup = p;\n            }\n            if (*p == '?' || *s == *p) {\n                ++s, ++p;\n            } else {\n                if (!sBackup) return false;\n                s = ++sBackup;\n                p = pBackup;\n            }\n        }\n        while (*p == '*') ++p;\n        return *s == '\\0' && *p == '\\0';\n    }\n};"
  },
  {
    "path": "WordBreak.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Oct 6, 2013\n Problem:    Word Break\n Difficulty: Easy\n Source:     http://oj.leetcode.com/problems/word-break/\n Notes:\n Given a string s and a dictionary of words dict, determine if s can be segmented into \n a space-separated sequence of one or more dictionary words.\n For example, given\n s = \"leetcode\",\n dict = [\"leet\", \"code\"].\n Return true because \"leetcode\" can be segmented as \"leet code\".\n\n Solution: dp.\n*/\n\nclass Solution {\npublic:\n    bool wordBreak(string s, unordered_set<string> &dict) {\n        int N = s.size();\n        bool canBreak[N+1];\n        memset(canBreak, false, sizeof(canBreak));\n        canBreak[0] = true;\n        for (int i = 1; i <= N; ++i) {\n            for (int j = i-1; j >= 0; --j) {\n                if (canBreak[j] && dict.find(s.substr(j, i-j)) != dict.end()) {\n                    canBreak[i] = true;\n                    break;\n                }\n            }\n        }\n        return canBreak[N];\n    }\n};\n"
  },
  {
    "path": "WordBreakII.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Oct 7, 2013\n Problem:    Word Break II\n Difficulty: Easy\n Source:     http://oj.leetcode.com/problems/word-break-ii/\n Notes:\n Given a string s and a dictionary of words dict, add spaces in s to \n construct a sentence where each word is a valid dictionary word.\n Return all such possible sentences.\n For example, given\n s = \"catsanddog\",\n dict = [\"cat\", \"cats\", \"and\", \"sand\", \"dog\"].\n A solution is [\"cats and dog\", \"cat sand dog\"].\n\n Solution: check before constructing the sentences.\n*/\n\nclass Solution {\npublic:\n    vector<string> wordBreak(string s, unordered_set<string> &dict) {\n        vector<string> res;\n        if (!wordBreakPossible(s, dict)) return res;\n        wordBreakRe(s, dict, 0, \"\", res);\n        return res;\n    }\n    \n    void wordBreakRe(const string &s, const unordered_set<string> &dict, \n                     int start, string sentence, vector<string> &res) {\n        if (start == s.size()) {\n            res.push_back(sentence);\n            return;\n        }\n        if (start != 0) sentence.push_back(' ');\n        for (int i = start; i < s.size(); ++i) {\n            string word = s.substr(start, i-start+1);\n            if (dict.find(word) == dict.end())\n                continue;\n            wordBreakRe(s, dict, i+1, sentence + word, res);\n        }\n    }\n    \n    bool wordBreakPossible(const string &s, const unordered_set<string> &dict) {\n        int N = s.size();\n        bool canBreak[N+1];\n        memset(canBreak, false, sizeof(canBreak));\n        canBreak[0] = true;\n        for (int i = 1; i <= N; ++i) {\n            for (int j = i-1; j >= 0; --j) {\n                if (canBreak[j] && dict.find(s.substr(j, i-j)) != dict.end()) {\n                    canBreak[i] = true;\n                    break;\n                }\n            }\n        }\n        return canBreak[N];\n    }\n};\n"
  },
  {
    "path": "WordLadder.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Jun 8, 2013\n Problem:    Word Ladder\n Difficulty: High\n Source:     http://leetcode.com/onlinejudge#question_127\n Notes:\n Given two words (start and end), and a dictionary, find the length of shortest transformation \n sequence from start to end, such that:\n Only one letter can be changed at a time\n Each intermediate word must exist in the dictionary\n For example,\n Given:\n start = \"hit\"\n end = \"cog\"\n dict = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\"]\n As one shortest transformation is \"hit\" -> \"hot\" -> \"dot\" -> \"dog\" -> \"cog\",\n return its length 5.\n Note:\n Return 0 if there is no such transformation sequence.\n All words have the same length.\n All words contain only lowercase alphabetic characters.\n\n Solution: BFS.\n*/\n\nclass Solution {\npublic:\n    int ladderLength(string start, string end, unordered_set<string> &dict) {\n        queue<pair<string, int>> q;\n        q.push(make_pair(start, 1));\n        while (!q.empty())\n        {\n            pair<string, int> front = q.front();\n            q.pop();\n            string word = front.first;\n            for (size_t i = 0; i < word.size(); i++)\n            {\n                char before = word[i];\n                for (char c = 'a'; c <= 'z'; c++)\n                {\n                    word[i] = c;\n                    if (word == end)\n                        return front.second + 1;\n                    if (dict.find(word) != dict.end())\n                    {\n                        q.push(make_pair(word, front.second + 1));\n                        dict.erase(word);\n                    }\n                }\n                word[i] = before;\n            }\n        }\n        return 0;\n    }\n};"
  },
  {
    "path": "WordLadderII.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Jul 8, 2013\n Problem:    Word Ladder II\n Difficulty: High\n Source:     http://leetcode.com/onlinejudge#question_126\n Notes:\n Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from start to end, such that:\n Only one letter can be changed at a time\n Each intermediate word must exist in the dictionary\n For example,\n Given:\n start = \"hit\"\n end = \"cog\"\n dict = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\"]\n Return\n [\n  [\"hit\",\"hot\",\"dot\",\"dog\",\"cog\"],\n  [\"hit\",\"hot\",\"lot\",\"log\",\"cog\"]\n ]\n Note:\n All words have the same length.\n All words contain only lowercase alphabetic characters.\n\n Solution: Idea is from blog: http://blog.csdn.net/niaokedaoren/article/details/8884938\n*/\n\nclass Solution {\npublic:\n    vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) {\n        map<string, vector<string>> traces; // If A->C and B->C, then traces[C] contains A and B.\n                                            // This is used for recovering the paths.\n        vector<unordered_set<string>> level(2);\n        int cur = 0;\n        int prev = 1;\n        level[cur].insert(start);\n        dict.insert(end);\n\n        while (true)\n        {\n            prev = !prev;\n            cur = !cur;\n            level[cur].clear();\n\n            // remove visited words. IMPORTANT!\n            for (unordered_set<string>::iterator it = level[prev].begin(); it != level[prev].end(); ++it)\n                dict.erase(*it);\n\n            for (unordered_set<string>::iterator it = level[prev].begin(); it != level[prev].end(); ++it)\n            {\n                string word = *it;\n                for (size_t i = 0; i < word.size(); i++) {\n                    char before = word[i];\n                    for (char c = 'a'; c <= 'z'; c++) {\n                        if (c == before)\n                            continue;\n                        word[i] = c;\n                        if (dict.find(word) != dict.end()) {\n                            traces[word].push_back(*it);\n                            level[cur].insert(word);\n                        }\n                    }\n                    word[i] = before;\n                }\n            }\n\n            if (level[cur].empty() || level[cur].count(end) > 0)\n                break;\n        }\n\n        vector<vector<string>> res;\n        vector<string> onePath;\n        if (!traces.empty())\n            buildResult(traces, res, onePath, end);\n\n        return res;\n    }\n\n    void buildResult(map<string, vector<string>> &traces, vector<vector<string>> &res, vector<string> &onePath, string word)\n    {\n        if (traces.count(word) == 0)\n        {\n            vector<string> copy(onePath);\n            copy.push_back(word);\n            reverse(copy.begin(), copy.end());\n            res.push_back(copy);\n            return;\n        }\n\n        const vector<string> &s = traces[word];\n        onePath.push_back(word);\n        for (vector<string>::const_iterator it = s.begin(); it != s.end(); ++it)\n            buildResult(traces, res, onePath, *it);\n        onePath.pop_back();\n    }\n};"
  },
  {
    "path": "WordSearch.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       May 13, 2013\n Update:     Sep 20, 2013\n Problem:    Word Search\n Difficulty: Easy\n Source:     http://leetcode.com/onlinejudge#question_79\n Notes:\n Given a 2D board and a word, find if the word exists in the grid.\n The word can be constructed from letters of sequentially adjacent cell, where \"adjacent\" cells are \n those horizontally or vertically neighboring. The same letter cell may not be used more than once.\n For example,\n Given board =\n [\n  [\"ABCE\"],\n  [\"SFCS\"],\n  [\"ADEE\"]\n ]\n word = \"ABCCED\", -> returns true,\n word = \"SEE\", -> returns true,\n word = \"ABCB\", -> returns false.\n\n Solution: DFS. (For 'visited', using two-dimensional array will be faster than vector<vector>.[90+ms->50+ms])\n */\n\nclass Solution {\npublic:\n    typedef vector<vector<char> > VECTOR2D;\n    \n    bool exist(VECTOR2D &board, string word) {\n        int N = board.size(), M = board[0].size();\n        VECTOR2D avail(N, vector<char>(M, 'o'));\n        for (int i = 0; i < N; ++i)\n            for (int j = 0; j < M; ++j)\n                if (existRe(board, word, 0, i, j, avail))\n                    return true;\n        return false;\n    }\n\n    bool existRe(const VECTOR2D &board, const string &word, int deep, int i, int j, VECTOR2D &avail)\n    {\n        int N = board.size(), M = board[0].size();\n        if (deep == word.size()) return true;\n        if (i < 0 || i >= N || j < 0 || j >= M) return false;\n        if (board[i][j] != word[deep] || avail[i][j] == 'x') return false;\n        \n        avail[i][j] = 'x';\n        if (existRe(board, word, deep + 1, i-1, j, avail)) return true;\n        if (existRe(board, word, deep + 1, i+1, j, avail)) return true;\n        if (existRe(board, word, deep + 1, i, j-1, avail)) return true;\n        if (existRe(board, word, deep + 1, i, j+1, avail)) return true;\n        avail[i][j] = 'o';\n        \n        return false;\n    }\n};"
  },
  {
    "path": "ZigZagConversion.h",
    "content": "/*\n Author:     Annie Kim, anniekim.pku@gmail.com\n Date:       Apr 7, 2013\n Update:     Dec 14, 2014\n Problem:    ZigZag Conversion\n Difficulty: Easy\n Source:     https://oj.leetcode.com/problems/zigzag-conversion/\n Notes:\n The string \"PAYPALISHIRING\" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)\n\n P   A   H   N\n A P L S I I G\n Y   I   R\n And then read line by line: \"PAHNAPLSIIGYIR\"\n Write the code that will take a string and make this conversion given a number of rows:\n\n string convert(string text, int nRows);\n convert(\"PAYPALISHIRING\", 3) should return \"PAHNAPLSIIGYIR\".\n\n Solution: ...\n */\n\nclass Solution {\npublic:\n    string convert(string s, int nRows) {\n        if(nRows <= 1) return s;\n        int n = s.size();\n        string res;\n        for(int i = 0;i < nRows; ++i){\n            for (int j = 0; j  + i < n; j += 2*nRows - 2) {\n                res.push_back(s[j+i]);\n                if (i == 0 || i == nRows - 1) continue;\n                if (j + 2*nRows - 2 - i < n)\n                    res.push_back(s[j + 2*nRows - 2 - i]);\n            }\n        }\n        return res;\n    }\n};"
  }
]