[
  {
    "path": ".devcontainer/devcontainer.json",
    "content": "{\n\t\"name\": \"TeX Live\",\n\t\"image\": \"soulmachine/texlive:latest\",\n\t\"extensions\": [\n\t\t\"James-Yu.latex-workshop\"\n\t]\n}"
  },
  {
    "path": ".gitignore",
    "content": "*.log\n*.toc\n*.aux\n*.idx\n*.out\n*.synctex.gz\n"
  },
  {
    "path": ".vscode/tasks.json",
    "content": "{\n    \"version\": \"2.0.0\",\n    \"tasks\": [\n        {\n            \"label\": \"lettcode-C++\",\n            \"type\": \"shell\",\n            \"command\": \"xelatex\",\n            \"args\": [\n                \"-synctex=1\",\n                \"-interaction=nonstopmode\",\n                \"leetcode-cpp.tex\"\n            ],\n            \"options\": {\n                \"cwd\": \"${workspaceFolder}/C++/\"\n            }\n        },\n        {\n            \"label\": \"lettcode-Java\",\n            \"type\": \"shell\",\n            \"command\": \"xelatex\",\n            \"args\": [\n                \"-synctex=1\",\n                \"-interaction=nonstopmode\",\n                \"leetcode-java.tex\"\n            ],\n            \"options\": {\n                \"cwd\": \"${workspaceFolder}/Java/\"\n            }\n        }\n    ]\n}"
  },
  {
    "path": "C++/README.md",
    "content": "# C++版\n\n## 编译\n\n```bash\ndocker run -it --rm -v $(pwd):/project -w /project soulmachine/texlive xelatex -interaction=nonstopmode leetcode-cpp.tex\n````\n"
  },
  {
    "path": "C++/abstract.tex",
    "content": "\\subsubsection{内容简介}\n本书的目标读者是准备去北美找工作的码农，也适用于在国内找工作的码农，以及刚接触ACM算法竞赛的新手。\n\n本书包含了 LeetCode Online Judge(\\myurl{http://leetcode.com/onlinejudge})所有题目的答案，\n所有代码经过精心编写，编码规范良好，适合读者反复揣摩，模仿，甚至在纸上默写。\n\n全书的代码，使用C++ 11的编写，并在 LeetCode Online Judge 上测试通过。本书中的代码规范，跟在公司中的工程规范略有不同，为了使代码短（方便迅速实现）:\n\n\\begindot\n\\item 所有代码都是单一文件。这是因为一般OJ网站，提交代码的时候只有一个文本框，如果还是\n按照标准做法，比如分为头文件.h和源代码.cpp，无法在网站上提交；\n\n\\item Shorter is better。能递归则一定不用栈；能用STL则一定不自己实现。\n\n\\item 不提倡防御式编程。不需要检查malloc()/new 返回的指针是否为nullptr；不需要检查内部函数入口参数的有效性。\n\\myenddot\n\n本手册假定读者已经学过《数据结构》\\footnote{《数据结构》，严蔚敏等著，清华大学出版社，\n\\myurl{http://book.douban.com/subject/2024655/}}，\n《算法》\\footnote{《Algorithms》，Robert Sedgewick, Addison-Wesley Professional, \\myurl{http://book.douban.com/subject/4854123/}}\n这两门课，熟练掌握C++或Java。\n\n\\subsubsection{GitHub地址}\n本书是开源的，GitHub地址：\\myurl{https://github.com/soulmachine/leetcode}\n\n\\subsubsection{北美求职微博群}\n我和我的小伙伴们在这里：\\myurl{http://q.weibo.com/1312378}\n"
  },
  {
    "path": "C++/chapBFS.tex",
    "content": "\\chapter{广度优先搜索}\n当题目看不出任何规律，既不能用分治，贪心，也不能用动规时，这时候万能方法——搜索，\n就派上用场了。搜索分为广搜和深搜，广搜里面又有普通广搜，双向广搜，A*搜索等。\n深搜里面又有普通深搜，回溯法等。\n\n广搜和深搜非常类似（除了在扩展节点这部分不一样），二者有相同的框架，如何表示状态？\n如何扩展状态？如何判重？尤其是判重，解决了这个问题，基本上整个问题就解决了。\n\n\n\\section{Word Ladder} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:word-ladder}\n\n\n\\subsubsection{描述}\nGiven two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:\n\\begindot\n\\item Only one letter can be changed at a time\n\\item Each intermediate word must exist in the dictionary\n\\myenddot\n\nFor example, Given:\n\n\\begin{Code}\nstart = \"hit\"\nend = \"cog\"\ndict = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\"]\n\\end{Code}\nAs one shortest transformation is \\code{\"hit\" -> \"hot\" -> \"dot\" -> \"dog\" -> \"cog\"}, return its length $5$.\n\nNote:\n\\begindot\n\\item Return 0 if there is no such transformation sequence.\n\\item All words have the same length.\n\\item All words contain only lowercase alphabetic characters.\n\\myenddot\n\n\n\\subsubsection{分析}\n求最短路径，用广搜。\n\n\n\\subsubsection{单队列}\n\\begin{Code}\n//LeetCode, Word Ladder\n// 时间复杂度O(n)，空间复杂度O(n)\nstruct state_t {\n    string word;\n    int level;\n\n    state_t() { word = \"\"; level = 0; }\n    state_t(const string& word, int level) {\n        this->word = word;\n        this->level = level;\n    }\n\n    bool operator==(const state_t &other) const {\n        return this->word == other.word;\n    }\n};\n\nnamespace std {\n    template<> struct hash<state_t> {\n    public:\n        size_t operator()(const state_t& s) const {\n            return str_hash(s.word);\n        }\n    private:\n        std::hash<std::string> str_hash;\n    };\n}\n\n\nclass Solution {\npublic:\n    int ladderLength(const string& start, const string &end,\n            const unordered_set<string> &dict) {\n        queue<state_t> q;\n        unordered_set<state_t> visited;  // 判重\n\n        auto state_is_valid = [&](const state_t& s) {\n            return dict.find(s.word) != dict.end() || s.word == end;\n        };\n        auto state_is_target = [&](const state_t &s) {return s.word == end; };\n        auto state_extend = [&](const state_t &s) {\n            unordered_set<state_t> result;\n\n            for (size_t i = 0; i < s.word.size(); ++i) {\n                state_t new_state(s.word, s.level + 1);\n                for (char c = 'a'; c <= 'z'; c++) {\n                    // 防止同字母替换\n                    if (c == new_state.word[i]) continue;\n\n                    swap(c, new_state.word[i]);\n\n                    if (state_is_valid(new_state) &&\n                        visited.find(new_state) == visited.end()) {\n                        result.insert(new_state);\n                    }\n                    swap(c, new_state.word[i]); // 恢复该单词\n                }\n            }\n\n            return result;\n        };\n\n        state_t start_state(start, 0);\n        q.push(start_state);\n        visited.insert(start_state);\n        while (!q.empty()) {\n            // 千万不能用 const auto&，pop() 会删除元素，\n            // 引用就变成了悬空引用\n            const auto state = q.front();\n            q.pop();\n\n            if (state_is_target(state)) {\n                return state.level + 1;\n            }\n\n            const auto& new_states = state_extend(state);\n            for (const auto& new_state : new_states) {\n                q.push(new_state);\n                visited.insert(new_state);\n            }\n        }\n        return 0;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{双队列}\n\\begin{Code}\n//LeetCode, Word Ladder\n// 时间复杂度O(n)，空间复杂度O(n)\nclass Solution {\npublic:\n    int ladderLength(const string& start, const string &end,\n            const unordered_set<string> &dict) {\n        queue<string> current, next;    // 当前层，下一层\n        unordered_set<string> visited;  // 判重\n\n        int level = -1;  // 层次\n\n        auto state_is_valid = [&](const string& s) {\n            return dict.find(s) != dict.end() || s == end;\n        };\n        auto state_is_target = [&](const string &s) {return s == end;};\n        auto state_extend = [&](const string &s) {\n            unordered_set<string> result;\n\n            for (size_t i = 0; i < s.size(); ++i) {\n                string new_word(s);\n                for (char c = 'a'; c <= 'z'; c++) {\n                    // 防止同字母替换\n                    if (c == new_word[i]) continue;\n\n                    swap(c, new_word[i]);\n\n                    if (state_is_valid(new_word) &&\n                        visited.find(new_word) == visited.end()) {\n                        result.insert(new_word);\n                    }\n                    swap(c, new_word[i]); // 恢复该单词\n                }\n            }\n\n            return result;\n        };\n\n        current.push(start);\n        visited.insert(start);\n        while (!current.empty()) {\n            ++level;\n            while (!current.empty()) {\n                // 千万不能用 const auto&，pop() 会删除元素，\n                // 引用就变成了悬空引用\n                const auto state = current.front();\n                current.pop();\n\n                if (state_is_target(state)) {\n                    return level + 1;\n                }\n\n                const auto& new_states = state_extend(state);\n                for (const auto& new_state : new_states) {\n                    next.push(new_state);\n                    visited.insert(new_state);\n                }\n            }\n            swap(next, current);\n        }\n        return 0;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\n\\begindot\n\\item Word Ladder II，见 \\S \\ref{sec:word-ladder-ii}\n\\myenddot\n\n\n\\section{Word Ladder II} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:word-ladder-ii}\n\n\n\\subsubsection{描述}\nGiven two words (start and end), and a dictionary, find all shortest transformation sequence(s) from start to end, such that:\n\\begindot\n\\item Only one letter can be changed at a time\n\\item Each intermediate word must exist in the dictionary\n\\myenddot\n\nFor example, Given:\n\\begin{Code}\nstart = \"hit\"\nend = \"cog\"\ndict = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\"]\n\\end{Code}\nReturn\n\\begin{Code}\n[\n    [\"hit\",\"hot\",\"dot\",\"dog\",\"cog\"],\n    [\"hit\",\"hot\",\"lot\",\"log\",\"cog\"]\n]\n\\end{Code}\n\nNote:\n\\begindot\n\\item All words have the same length.\n\\item All words contain only lowercase alphabetic characters.\n\\myenddot\n\n\n\\subsubsection{分析}\n跟 Word Ladder比，这题是求路径本身，不是路径长度，也是BFS，略微麻烦点。\n\n求一条路径和求所有路径有很大的不同，求一条路径，每个状态节点只需要记录一个前驱即可；求所有路径时，有的状态节点可能有多个父节点，即要记录多个前驱。\n\n如果当前路径长度已经超过当前最短路径长度，可以中止对该路径的处理，因为我们要找的是最短路径。\n\n\n\\subsubsection{单队列}\n\n\\begin{Code}\n//LeetCode, Word Ladder II\n// 时间复杂度O(n)，空间复杂度O(n)\nstruct state_t {\n    string word;\n    int level;\n\n    state_t() { word = \"\"; level = 0; }\n    state_t(const string& word, int level) {\n        this->word = word;\n        this->level = level;\n    }\n\n    bool operator==(const state_t &other) const {\n        return this->word == other.word;\n    }\n};\n\nnamespace std {\n    template<> struct hash<state_t> {\n    public:\n        size_t operator()(const state_t& s) const {\n            return str_hash(s.word);\n        }\n    private:\n        std::hash<std::string> str_hash;\n    };\n}\n\n\nclass Solution {\npublic:\n    vector<vector<string> > findLadders(const string& start,\n        const string& end, const unordered_set<string> &dict) {\n        queue<state_t> q;\n        unordered_set<state_t> visited; // 判重\n        unordered_map<state_t, vector<state_t> > father; // DAG\n\n        auto state_is_valid = [&](const state_t& s) {\n            return dict.find(s.word) != dict.end() || s.word == end;\n        };\n        auto state_is_target = [&](const state_t &s) {return s.word == end; };\n        auto state_extend = [&](const state_t &s) {\n            unordered_set<state_t> result;\n\n            for (size_t i = 0; i < s.word.size(); ++i) {\n                state_t new_state(s.word, s.level + 1);\n                for (char c = 'a'; c <= 'z'; c++) {\n                    // 防止同字母替换\n                    if (c == new_state.word[i]) continue;\n\n                    swap(c, new_state.word[i]);\n\n                    if (state_is_valid(new_state)) {\n                        auto visited_iter = visited.find(new_state);\n\n                        if (visited_iter != visited.end()) {\n                            if (visited_iter->level < new_state.level) {\n                                // do nothing\n                            } else if (visited_iter->level == new_state.level) {\n                                result.insert(new_state);\n                            } else { // not possible\n                                throw std::logic_error(\"not possible to get here\");\n                            }\n                        } else {\n                            result.insert(new_state);\n                        }\n                    }\n                    swap(c, new_state.word[i]); // 恢复该单词\n                }\n            }\n\n            return result;\n        };\n\n        vector<vector<string>> result;\n        state_t start_state(start, 0);\n        q.push(start_state);\n        visited.insert(start_state);\n        while (!q.empty()) {\n            // 千万不能用 const auto&，pop() 会删除元素，\n            // 引用就变成了悬空引用\n            const auto state = q.front();\n            q.pop();\n\n            // 如果当前路径长度已经超过当前最短路径长度，\n            // 可以中止对该路径的处理，因为我们要找的是最短路径\n            if (!result.empty() && state.level + 1 > result[0].size()) break;\n\n            if (state_is_target(state)) {\n                vector<string> path;\n                gen_path(father, start_state, state, path, result);\n                continue;\n            }\n            // 必须挪到下面，比如同一层A和B两个节点均指向了目标节点，\n            // 那么目标节点就会在q中出现两次，输出路径就会翻倍\n            // visited.insert(state);\n\n            // 扩展节点\n            const auto& new_states = state_extend(state);\n            for (const auto& new_state : new_states) {\n                if (visited.find(new_state) == visited.end()) {\n                    q.push(new_state);\n                }\n                visited.insert(new_state);\n                father[new_state].push_back(state);\n            }\n        }\n\n        return result;\n    }\nprivate:\n    void gen_path(unordered_map<state_t, vector<state_t> > &father,\n        const state_t &start, const state_t &state, vector<string> &path,\n        vector<vector<string> > &result) {\n        path.push_back(state.word);\n        if (state == start) {\n            if (!result.empty()) {\n                if (path.size() < result[0].size()) {\n                    result.clear();\n                    result.push_back(path);\n                    reverse(result.back().begin(), result.back().end());\n                } else if (path.size() == result[0].size()) {\n                    result.push_back(path);\n                    reverse(result.back().begin(), result.back().end());\n                } else { // not possible\n                    throw std::logic_error(\"not possible to get here \");\n                }\n            } else {\n                result.push_back(path);\n                reverse(result.back().begin(), result.back().end());\n            }\n\n        } else {\n            for (const auto& f : father[state]) {\n                gen_path(father, start, f, path, result);\n            }\n        }\n        path.pop_back();\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{双队列}\n\n\\begin{Code}\n//LeetCode, Word Ladder II\n// 时间复杂度O(n)，空间复杂度O(n)\nclass Solution {\npublic:\n    vector<vector<string> > findLadders(const string& start,\n            const string& end, const unordered_set<string> &dict) {\n        // 当前层，下一层，用unordered_set是为了去重，例如两个父节点指向\n        // 同一个子节点，如果用vector, 子节点就会在next里出现两次，其实此\n        // 时 father 已经记录了两个父节点，next里重复出现两次是没必要的\n        unordered_set<string> current, next;\n        unordered_set<string> visited; // 判重\n        unordered_map<string, vector<string> > father; // DAG\n\n        int level = -1;  // 层次\n\n        auto state_is_valid = [&](const string& s) {\n            return dict.find(s) != dict.end() || s == end;\n        };\n        auto state_is_target = [&](const string &s) {return s == end;};\n        auto state_extend = [&](const string &s) {\n            unordered_set<string> result;\n\n            for (size_t i = 0; i < s.size(); ++i) {\n                string new_word(s);\n                for (char c = 'a'; c <= 'z'; c++) {\n                    // 防止同字母替换\n                    if (c == new_word[i]) continue;\n\n                    swap(c, new_word[i]);\n\n                    if (state_is_valid(new_word) &&\n                            visited.find(new_word) == visited.end()) {\n                        result.insert(new_word);\n                    }\n                    swap(c, new_word[i]); // 恢复该单词\n                }\n            }\n\n            return result;\n        };\n\n        vector<vector<string> > result;\n        current.insert(start);\n        while (!current.empty()) {\n            ++ level;\n            // 如果当前路径长度已经超过当前最短路径长度，可以中止对该路径的\n            // 处理，因为我们要找的是最短路径\n            if (!result.empty() && level+1 > result[0].size()) break;\n\n            // 1. 延迟加入visited, 这样才能允许两个父节点指向同一个子节点\n            // 2. 一股脑current 全部加入visited, 是防止本层前一个节点扩展\n            // 节点时，指向了本层后面尚未处理的节点，这条路径必然不是最短的\n            for (const auto& state : current)\n                visited.insert(state);\n            for (const auto& state : current) {\n                if (state_is_target(state)) {\n                    vector<string> path;\n                    gen_path(father, path, start, state, result);\n                    continue;\n                }\n\n                const auto new_states = state_extend(state);\n                for (const auto& new_state : new_states) {\n                    next.insert(new_state);\n                    father[new_state].push_back(state);\n                }\n            }\n\n            current.clear();\n            swap(current, next);\n        }\n\n        return result;\n    }\nprivate:\n    void gen_path(unordered_map<string, vector<string> > &father,\n            vector<string> &path, const string &start, const string &word,\n            vector<vector<string> > &result) {\n        path.push_back(word);\n        if (word == start) {\n            if (!result.empty()) {\n                if (path.size() < result[0].size()) {\n                    result.clear();\n                    result.push_back(path);\n                } else if(path.size() == result[0].size()) {\n                    result.push_back(path);\n                } else {\n                    // not possible\n                    throw std::logic_error(\"not possible to get here\");\n                }\n            } else {\n                result.push_back(path);\n            }\n            reverse(result.back().begin(), result.back().end());\n        } else {\n            for (const auto& f : father[word]) {\n                gen_path(father, path, start, f, result);\n            }\n        }\n        path.pop_back();\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{图的广搜}\n\n本题还可以看做是图上的广搜。给定了字典 \\fn{dict}，可以基于它画出一个无向图，表示单词之间可以互相转换。本题的本质就是已知起点和终点，在图上找出所有最短路径。\n\n\\begin{Code}\n//LeetCode, Word Ladder II\n// 时间复杂度O(n)，空间复杂度O(n)\nclass Solution {\npublic:\n    vector<vector<string> > findLadders(const string& start,\n            const string &end, const unordered_set<string> &dict) {\n        const auto& g = build_graph(dict);\n        vector<state_t*> pool;\n        queue<state_t*> q; // 未处理的节点\n        // value 是所在层次\n        unordered_map<string, int> visited;\n\n        auto state_is_target = [&](const state_t *s) {return s->word == end; };\n\n        vector<vector<string>> result;\n        q.push(create_state(nullptr, start, 0, pool));\n        while (!q.empty()) {\n            state_t* state = q.front();\n            q.pop();\n\n            // 如果当前路径长度已经超过当前最短路径长度，\n            // 可以中止对该路径的处理，因为我们要找的是最短路径\n            if (!result.empty() && state->level+1 > result[0].size()) break;\n\n            if (state_is_target(state)) {\n                const auto& path = gen_path(state);\n                if (result.empty()) {\n                    result.push_back(path);\n                } else {\n                    if (path.size() < result[0].size()) {\n                        result.clear();\n                        result.push_back(path);\n                    } else if (path.size() == result[0].size()) {\n                        result.push_back(path);\n                    } else {\n                        // not possible\n                        throw std::logic_error(\"not possible to get here\");\n                    }\n                }\n                continue;\n            }\n            visited[state->word] = state->level;\n\n            // 扩展节点\n            auto iter = g.find(state->word);\n            if (iter == g.end()) continue;\n\n            for (const auto& neighbor : iter->second) {\n                auto visited_iter = visited.find(neighbor);\n\n                if (visited_iter != visited.end() && \n                    visited_iter->second < state->level + 1) {\n                    continue;\n                }\n\n                q.push(create_state(state, neighbor, state->level + 1, pool));\n            }\n        }\n\n        // release all states\n        for (auto state : pool) {\n            delete state;\n        }\n        return result;\n    }\n\nprivate:\n    struct state_t {\n        state_t* father;\n        string word;\n        int level; // 所在层次，从0开始编号\n\n        state_t(state_t* father_, const string& word_, int level_) :\n            father(father_), word(word_), level(level_) {}\n    };\n\n    state_t* create_state(state_t* parent, const string& value,\n            int length, vector<state_t*>& pool) {\n        state_t* node = new state_t(parent, value, length);\n        pool.push_back(node);\n\n        return node;\n    }\n    vector<string> gen_path(const state_t* node) {\n        vector<string> path;\n\n        while(node != nullptr) {\n            path.push_back(node->word);\n            node = node->father;\n        }\n\n        reverse(path.begin(), path.end());\n        return path;\n    }\n\n    unordered_map<string, unordered_set<string> > build_graph(\n            const unordered_set<string>& dict) {\n        unordered_map<string, unordered_set<string> > adjacency_list;\n\n        for (const auto& word : dict) {\n            for (size_t i = 0; i < word.size(); ++i) {\n                string new_word(word);\n                for (char c = 'a'; c <= 'z'; c++) {\n                    // 防止同字母替换\n                    if (c == new_word[i]) continue;\n\n                    swap(c, new_word[i]);\n\n                    if ((dict.find(new_word) != dict.end())) {\n                        auto iter = adjacency_list.find(word);\n                        if (iter != adjacency_list.end()) {\n                            iter->second.insert(new_word);\n                        } else {\n                            adjacency_list.insert(pair<string,\n                                unordered_set<string>>(word, unordered_set<string>()));\n                            adjacency_list[word].insert(new_word);\n                        }\n                    }\n                    swap(c, new_word[i]); // 恢复该单词\n                }\n            }\n        }\n        return adjacency_list;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\n\\begindot\n\\item Word Ladder，见 \\S \\ref{sec:word-ladder}\n\\myenddot\n\n\n\\section{Surrounded Regions} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:surrounded-regions}\n\n\n\\subsubsection{描述}\nGiven a 2D board containing \\fn{'X'} and \\fn{'O'}, capture all regions surrounded by \\fn{'X'}.\n\nA region is captured by flipping all \\fn{'O'}s into \\fn{'X'}s in that surrounded region .\n\nFor example,\n\\begin{Code}\nX X X X\nX O O X\nX X O X\nX O X X\n\\end{Code}\n\nAfter running your function, the board should be:\n\\begin{Code}\nX X X X\nX X X X\nX X X X\nX O X X\n\\end{Code}\n\n\n\\subsubsection{分析}\n广搜。从上下左右四个边界往里走，凡是能碰到的\\fn{'O'}，都是跟边界接壤的，应该保留。\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Surrounded Regions\n// BFS，时间复杂度O(n)，空间复杂度O(n)\nclass Solution {\npublic:\n    void solve(vector<vector<char>> &board) {\n        if (board.empty()) return;\n\n        const int m = board.size();\n        const int n = board[0].size();\n        for (int i = 0; i < n; i++) {\n            bfs(board, 0, i);\n            bfs(board, m - 1, i);\n        }\n        for (int j = 1; j < m - 1; j++) {\n            bfs(board, j, 0);\n            bfs(board, j, n - 1);\n        }\n        for (int i = 0; i < m; i++)\n            for (int j = 0; j < n; j++)\n                if (board[i][j] == 'O')\n                    board[i][j] = 'X';\n                else if (board[i][j] == '+')\n                    board[i][j] = 'O';\n    }\nprivate:\n    void bfs(vector<vector<char>> &board, int i, int j) {\n        typedef pair<int, int> state_t;\n        queue<state_t> q;\n        const int m = board.size();\n        const int n = board[0].size();\n\n        auto state_is_valid = [&](const state_t &s) {\n            const int x = s.first;\n            const int y = s.second;\n            if (x < 0 || x >= m || y < 0 || y >= n || board[x][y] != 'O')\n                return false;\n            return true;\n        };\n\n        auto state_extend = [&](const state_t &s) {\n            vector<state_t> result;\n            const int x = s.first;\n            const int y = s.second;\n            // 上下左右\n            const state_t new_states[4] = {{x-1,y}, {x+1,y},\n                    {x,y-1}, {x,y+1}};\n            for (int k = 0; k < 4;  ++k) {\n                if (state_is_valid(new_states[k])) {\n                    // 既有标记功能又有去重功能\n                    board[new_states[k].first][new_states[k].second] = '+';\n                    result.push_back(new_states[k]);\n                }\n            }\n\n            return result;\n        };\n\n        state_t start = { i, j };\n        if (state_is_valid(start)) {\n            board[i][j] = '+';\n            q.push(start);\n        }\n        while (!q.empty()) {\n            auto cur = q.front();\n            q.pop();\n            auto new_states = state_extend(cur);\n            for (auto s : new_states) q.push(s);\n        }\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\n\\begindot\n\\item 无\n\\myenddot\n\n\n\\section{小结} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:bfs-template}\n\n\n\\subsection{适用场景}\n\n\\textbf{输入数据}：没什么特征，不像深搜，需要有“递归”的性质。如果是树或者图，概率更大。\n\n\\textbf{状态转换图}：树或者DAG图。\n\n\\textbf{求解目标}：求最短。\n\n\n\\subsection{思考的步骤}\n\\begin{enumerate}\n\\item 是求路径长度，还是路径本身（或动作序列）？\n    \\begin{enumerate}\n    \\item 如果是求路径长度，则状态里面要存路径长度（或双队列+一个全局变量）\n    \\item 如果是求路径本身或动作序列\n        \\begin{enumerate}\n            \\item 要用一棵树存储宽搜过程中的路径\n            \\item 是否可以预估状态个数的上限？能够预估状态总数，则开一个大数组，用树的双亲表示法；如果不能预估状态总数，则要使用一棵通用的树。这一步也是第4步的必要不充分条件。\n        \\end{enumerate}\n    \\end{enumerate}\n\n\\item 如何表示状态？即一个状态需要存储哪些些必要的数据，才能够完整提供如何扩展到下一步状态的所有信息。一般记录当前位置或整体局面。\n\n\\item 如何扩展状态？这一步跟第2步相关。状态里记录的数据不同，扩展方法就不同。对于固定不变的数据结构（一般题目直接给出，作为输入数据），如二叉树，图等，扩展方法很简单，直接往下一层走，对于隐式图，要先在第1步里想清楚状态所带的数据，想清楚了这点，那如何扩展就很简单了。\n\n\\item 如何判断重复？如果状态转换图是一颗树，则永远不会出现回路，不需要判重；如果状态转换图是一个图（这时候是一个图上的BFS），则需要判重。\n    \\begin{enumerate}\n    \\item 如果是求最短路径长度或一条路径，则只需要让“点”（即状态）不重复出现，即可保证不出现回路\n    \\item 如果是求所有路径，注意此时，状态转换图是DAG，即允许两个父节点指向同一个子节点。具体实现时，每个节点要\\textbf{“延迟”}加入到已访问集合\\fn{visited}，要等一层全部访问完后，再加入到\\fn{visited}集合。\n    \\item 具体实现\n        \\begin{enumerate}\n        \\item 状态是否存在完美哈希方案？即将状态一一映射到整数，互相之间不会冲突。\n        \\item 如果不存在，则需要使用通用的哈希表（自己实现或用标准库，例如\\fn{unordered_set}）来判重；自己实现哈希表的话，如果能够预估状态个数的上限，则可以开两个数组，head和next，表示哈希表，参考第 \\S \\ref{subsec:eightDigits}节方案2。\n        \\item 如果存在，则可以开一个大布尔数组，来判重，且此时可以精确计算出状态总数，而不仅仅是预估上限。\n        \\end{enumerate}\n    \\end{enumerate}\n\n\\item 目标状态是否已知？如果题目已经给出了目标状态，可以带来很大便利，这时候可以从起始状态出发，正向广搜；也可以从目标状态出发，逆向广搜；也可以同时出发，双向广搜。\n\\end{enumerate}\n\n\n\\subsection{代码模板}\n广搜需要一个队列，用于一层一层扩展，一个hashset，用于判重，一棵树（只求长度时不需要），用于存储整棵树。\n\n对于队列，可以用\\fn{queue}，也可以把\\fn{vector}当做队列使用。当求长度时，有两种做法：\n\\begin{enumerate}\n\\item 只用一个队列，但在状态结构体\\fn{state_t}里增加一个整数字段\\fn{level}，表示当前所在的层次，当碰到目标状态，直接输出\\fn{level}即可。这个方案，可以很容易的变成A*算法，把\\fn{queue}替换为\\fn{priority_queue}即可。\n\\item 用两个队列，\\fn{current, next}，分别表示当前层次和下一层，另设一个全局整数\\fn{level}，表示层数（也即路径长度），当碰到目标状态，输出\\fn{level}即可。这个方案，状态里可以不存路径长度，只需全局设置一个整数\\fn{level}，比较节省内存；\n\\end{enumerate}\n\n对于hashset，如果有完美哈希方案，用布尔数组(\\fn{bool visited[STATE_MAX]}或\\fn{vector<bool> visited(STATE_MAX, false)})来表示；如果没有，可以用STL里的\\fn{set}或\\fn{unordered_set}。\n\n对于树，如果用STL，可以用\\fn{unordered_map<state_t, state_t > father}表示一颗树，代码非常简洁。如果能够预估状态总数的上限（设为STATE_MAX），可以用数组(\\fn{state_t nodes[STATE_MAX]})，即树的双亲表示法来表示树，效率更高，当然，需要写更多代码。\n\n\n\\subsubsection{如何表示状态}\n\n\\begin{Codex}[label=bfs_common.h]\n/** 状态 */\nstruct state_t {\n    int data1;  /** 状态的数据，可以有多个字段. */\n    int data2;  /** 状态的数据，可以有多个字段. */\n    // dataN;   /** 其他字段 */\n    int action; /** 由父状态移动到本状态的动作，求动作序列时需要. */\n    int level;  /** 所在的层次（从0开始），也即路径长度-1，求路径长度时需要；\n                    不过，采用双队列时不需要本字段，只需全局设一个整数 */\n    bool operator==(const state_t &other) const {\n        return true;  // 根据具体问题实现\n    }\n};\n\n// 定义hash函数\n\n// 方法1：模板特化，当hash函数只需要状态本身，不需要其他数据时，用这个方法比较简洁\nnamespace std {\ntemplate<> struct hash<state_t> {\n    size_t operator()(const state_t & x) const {\n        return 0; // 根据具体问题实现\n    }\n};\n}\n\n// 方法2：函数对象，如果hash函数需要运行时数据，则用这种方法\nclass Hasher {\npublic:\n    Hasher(int _m) : m(_m) {};\n    size_t operator()(const state_t &s) const {\n        return 0; // 根据具体问题实现\n    }\nprivate:\n    int m; // 存放外面传入的数据\n};\n\n/**\n * @brief 反向生成路径，求一条路径.\n * @param[in] father 树\n * @param[in] target 目标节点\n * @return 从起点到target的路径\n */\nvector<state_t> gen_path(const unordered_map<state_t, state_t> &father,\n        const state_t &target) {\n    vector<state_t> path;\n    path.push_back(target);\n\n    for (state_t cur = target; father.find(cur) != father.end(); \n            cur = father.at(cur))\n        path.push_back(cur);\n\n    reverse(path.begin(), path.end());\n\n    return path;\n}\n\n/**\n * 反向生成路径，求所有路径.\n * @param[in] father 存放了所有路径的树\n * @param[in] start 起点\n * @param[in] state 终点\n * @return 从起点到终点的所有路径\n */\nvoid gen_path(unordered_map<state_t, vector<state_t> > &father,\n        const string &start, const state_t& state, vector<state_t> &path,\n        vector<vector<state_t> > &result) {\n    path.push_back(state);\n    if (state == start) {\n        if (!result.empty()) {\n            if (path.size() < result[0].size()) {\n                result.clear();\n                result.push_back(path);\n            } else if(path.size() == result[0].size()) {\n                result.push_back(path);\n            } else {\n                // not possible\n                throw std::logic_error(\"not possible to get here\");\n            }\n        } else {\n            result.push_back(path);\n        }\n        reverse(result.back().begin(), result.back().end());\n    } else {\n        for (const auto& f : father[state]) {\n            gen_path(father, start, f, path, result);\n        }\n    }\n    path.pop_back();\n}\n\\end{Codex}\n\n\n\\subsubsection{求最短路径长度或一条路径}\n\n\\textbf{单队列的写法}\n\n\\begin{Codex}[label=bfs_template.cpp]\n#include \"bfs_common.h\"\n\n/**\n * @brief 广搜，只用一个队列.\n * @param[in] start 起点\n * @param[in] data 输入数据\n * @return 从起点到目标状态的一条最短路径\n */\nvector<state_t> bfs(state_t &start, const vector<vector<int>> &grid) {\n    queue<state_t> q; // 队列\n    unordered_set<state_t> visited; // 判重\n    unordered_map<state_t, state_t> father; // 树，求路径本身时才需要\n\n    // 判断状态是否合法\n    auto state_is_valid = [&](const state_t &s) { /*...*/ };\n\n    // 判断当前状态是否为所求目标\n    auto state_is_target = [&](const state_t &s) { /*...*/ };\n\n    // 扩展当前状态\n    auto state_extend = [&](const state_t &s) {\n        unordered_set<state_t> result;\n        for (/*...*/) {\n            const state_t new_state = /*...*/;\n            if (state_is_valid(new_state) && \n                    visited.find(new_state) != visited.end()) {\n                result.insert(new_state);\n            }\n        }\n        return result;\n    };\n\n    assert (start.level == 0);\n    q.push(start);\n    while (!q.empty()) {\n        // 千万不能用 const auto&，pop() 会删除元素，\n        // 引用就变成了悬空引用\n        const state_t state = q.front();\n        q.pop();\n        visited.insert(state);\n\n        // 访问节点\n        if (state_is_target(state)) {\n            return return gen_path(father, target); // 求一条路径\n            // return state.level + 1; // 求路径长度\n        }\n\n        // 扩展节点\n        vector<state_t> new_states = state_extend(state);\n        for (const auto& new_state : new_states) {\n            q.push(new_state);\n            father[new_state] = state;  // 求一条路径\n            // visited.insert(state); // 优化：可以提前加入 visited 集合，\n            // 从而缩小状态扩展。这时 q 的含义略有变化，里面存放的是处理了一半\n            // 的节点：已经加入了visited，但还没有扩展。别忘记 while循环开始\n            // 前，要加一行代码, visited.insert(start)\n        }\n    }\n\n    return vector<state_t>();\n    //return 0;\n}\n\\end{Codex}\n\n\n\\textbf{双队列的写法}\n\\begin{Codex}[label=bfs_template1.cpp]\n#include \"bfs_common.h\"\n\n/**\n * @brief 广搜，使用两个队列.\n * @param[in] start 起点\n * @param[in] data 输入数据\n * @return 从起点到目标状态的一条最短路径\n */\nvector<state_t> bfs(const state_t &start, const type& data) {\n    queue<state_t> next, current; // 当前层，下一层\n    unordered_set<state_t> visited; // 判重\n    unordered_map<state_t, state_t> father; // 树，求路径本身时才需要\n\n    int level = -1;  // 层次\n\n    // 判断状态是否合法\n    auto state_is_valid = [&](const state_t &s) { /*...*/ };\n\n    // 判断当前状态是否为所求目标\n    auto state_is_target = [&](const state_t &s) { /*...*/ };\n\n    // 扩展当前状态\n    auto state_extend = [&](const state_t &s) {\n        unordered_set<state_t> result;\n        for (/*...*/) {\n            const state_t new_state = /*...*/;\n            if (state_is_valid(new_state) && \n                    visited.find(new_state) != visited.end()) {\n                result.insert(new_state);\n            }\n        }\n        return result;\n    };\n\n    current.push(start);\n    while (!current.empty()) {\n        ++level;\n        while (!current.empty()) {\n            // 千万不能用 const auto&，pop() 会删除元素，\n            // 引用就变成了悬空引用\n            const auto state = current.front();\n            current.pop();\n            visited.insert(state);\n\n            if (state_is_target(state)) {\n                return return gen_path(father, state); // 求一条路径\n                // return state.level + 1; // 求路径长度\n            }\n\n            const auto& new_states = state_extend(state);\n            for (const auto& new_state : new_states) {\n                next.push(new_state);\n                father[new_state] = state;\n                // visited.insert(state); // 优化：可以提前加入 visited 集合，\n                // 从而缩小状态扩展。这时 current 的含义略有变化，里面存放的是处\n                // 理了一半的节点：已经加入了visited，但还没有扩展。别忘记 while\n                // 循环开始前，要加一行代码, visited.insert(start)\n            }\n        }\n        swap(next, current); //!!! 交换两个队列\n    }\n\n    return vector<state_t>();\n    // return 0;\n}\n\\end{Codex}\n\n\n\\subsubsection{求所有路径}\n\n\\textbf{单队列}\n\n\\begin{Codex}[label=bfs_template.cpp]\n/**\n * @brief 广搜，使用一个队列.\n * @param[in] start 起点\n * @param[in] data 输入数据\n * @return 从起点到目标状态的所有最短路径\n */\nvector<vector<state_t> > bfs(const state_t &start, const type& data) {\n    queue<state_t> q;\n    unordered_set<state_t> visited; // 判重\n    unordered_map<state_t, vector<state_t> > father; // DAG\n\n    auto state_is_valid = [&](const state_t& s) { /*...*/ };\n    auto state_is_target = [&](const state_t &s) { /*...*/ };\n    auto state_extend = [&](const state_t &s) {\n        unordered_set<state_t> result;\n        for (/*...*/) {\n            const state_t new_state = /*...*/;\n            if (state_is_valid(new_state)) {\n                auto visited_iter = visited.find(new_state);\n\n                if (visited_iter != visited.end()) {\n                    if (visited_iter->level < new_state.level) {\n                        // do nothing\n                    } else if (visited_iter->level == new_state.level) {\n                        result.insert(new_state);\n                    } else { // not possible\n                        throw std::logic_error(\"not possible to get here\");\n                    }\n                } else {\n                    result.insert(new_state);\n                }\n            }\n        }\n\n        return result;\n    };\n\n    vector<vector<string>> result;\n    state_t start_state(start, 0);\n    q.push(start_state);\n    visited.insert(start_state);\n    while (!q.empty()) {\n        // 千万不能用 const auto&，pop() 会删除元素，\n        // 引用就变成了悬空引用\n        const auto state = q.front();\n        q.pop();\n\n        // 如果当前路径长度已经超过当前最短路径长度，\n        // 可以中止对该路径的处理，因为我们要找的是最短路径\n        if (!result.empty() && state.level + 1 > result[0].size()) break;\n\n        if (state_is_target(state)) {\n            vector<string> path;\n            gen_path(father, start_state, state, path, result);\n            continue;\n        }\n        // 必须挪到下面，比如同一层A和B两个节点均指向了目标节点，\n        // 那么目标节点就会在q中出现两次，输出路径就会翻倍\n        // visited.insert(state);\n\n        // 扩展节点\n        const auto& new_states = state_extend(state);\n        for (const auto& new_state : new_states) {\n            if (visited.find(new_state) == visited.end()) {\n                q.push(new_state);\n            }\n            visited.insert(new_state);\n            father[new_state].push_back(state);\n        }\n    }\n\n    return result;\n}\n\\end{Codex}\n\n\n\\textbf{双队列的写法}\n\n\\begin{Codex}[label=bfs_template.cpp]\n#include \"bfs_common.h\"\n\n/**\n * @brief 广搜，使用两个队列.\n * @param[in] start 起点\n * @param[in] data 输入数据\n * @return 从起点到目标状态的所有最短路径\n */\nvector<vector<state_t> > bfs(const state_t &start, const type& data) {\n    // 当前层，下一层，用unordered_set是为了去重，例如两个父节点指向\n    // 同一个子节点，如果用vector, 子节点就会在next里出现两次，其实此\n    // 时 father 已经记录了两个父节点，next里重复出现两次是没必要的\n    unordered_set<string> current, next;\n    unordered_set<state_t> visited; // 判重\n    unordered_map<state_t, vector<state_t> > father; // DAG\n\n    int level = -1;  // 层次\n\n    // 判断状态是否合法\n    auto state_is_valid = [&](const state_t &s) { /*...*/ };\n\n    // 判断当前状态是否为所求目标\n    auto state_is_target = [&](const state_t &s) { /*...*/ };\n\n    // 扩展当前状态\n    auto state_extend = [&](const state_t &s) {\n        unordered_set<state_t> result;\n        for (/*...*/) {\n            const state_t new_state = /*...*/;\n            if (state_is_valid(new_state) && \n                    visited.find(new_state) != visited.end()) {\n                result.insert(new_state);\n            }\n        }\n        return result;\n    };\n\n    vector<vector<state_t> > result;\n    current.insert(start);\n    while (!current.empty()) {\n        ++ level;\n        // 如果当前路径长度已经超过当前最短路径长度，可以中止对该路径的\n        // 处理，因为我们要找的是最短路径\n        if (!result.empty() && level+1 > result[0].size()) break;\n\n        // 1. 延迟加入visited, 这样才能允许两个父节点指向同一个子节点\n        // 2. 一股脑current 全部加入visited, 是防止本层前一个节点扩展\n        // 节点时，指向了本层后面尚未处理的节点，这条路径必然不是最短的\n        for (const auto& state : current)\n            visited.insert(state);\n        for (const auto& state : current) {\n            if (state_is_target(state)) {\n                vector<string> path;\n                gen_path(father, path, start, state, result);\n                continue;\n            }\n\n            const auto new_states = state_extend(state);\n            for (const auto& new_state : new_states) {\n                next.insert(new_state);\n                father[new_state].push_back(state);\n            }\n        }\n\n        current.clear();\n        swap(current, next);\n    }\n\n    return result;\n}\n\\end{Codex}\n\n"
  },
  {
    "path": "C++/chapBruteforce.tex",
    "content": "\\chapter{暴力枚举法}\n\n\n\\section{Subsets} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:subsets}\n\n\n\\subsubsection{描述}\nGiven a set of distinct integers, $S$, return all possible subsets.\n\nNote:\n\\begindot\n\\item Elements in a subset must be in non-descending order.\n\\item The solution set must not contain duplicate subsets.\n\\myenddot\n\nFor example, If \\code{S = [1,2,3]}, a solution is:\n\\begin{Code}\n[\n  [3],\n  [1],\n  [2],\n  [1,2,3],\n  [1,3],\n  [2,3],\n  [1,2],\n  []\n]\n\\end{Code}\n\n\n\\subsection{递归}\n\n\n\\subsubsection{增量构造法}\n每个元素，都有两种选择，选或者不选。\n\n\\begin{Code}\n// LeetCode, Subsets\n// 增量构造法，深搜，时间复杂度O(2^n)，空间复杂度O(n)\nclass Solution {\npublic:\n    vector<vector<int> > subsets(vector<int> &S) {\n        sort(S.begin(), S.end());  // 输出要求有序\n        vector<vector<int> > result;\n        vector<int> path;\n        subsets(S, path, 0, result);\n        return result;\n    }\n\nprivate:\n    static void subsets(const vector<int> &S, vector<int> &path, int step,\n            vector<vector<int> > &result) {\n        if (step == S.size()) {\n            result.push_back(path);\n            return;\n        }\n        // 不选S[step]\n        subsets(S, path, step + 1, result);\n        // 选S[step]\n        path.push_back(S[step]);\n        subsets(S, path, step + 1, result);\n        path.pop_back();\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{位向量法}\n开一个位向量\\fn{bool selected[n]}，每个元素可以选或者不选。\n\n\\begin{Code}\n// LeetCode, Subsets\n// 位向量法，深搜，时间复杂度O(2^n)，空间复杂度O(n)\nclass Solution {\npublic:\n    vector<vector<int> > subsets(vector<int> &S) {\n        sort(S.begin(), S.end());  // 输出要求有序\n\n        vector<vector<int> > result;\n        vector<bool> selected(S.size(), false);\n        subsets(S, selected, 0, result);\n        return result;\n    }\n\nprivate:\n    static void subsets(const vector<int> &S, vector<bool> &selected, int step,\n            vector<vector<int> > &result) {\n        if (step == S.size()) {\n            vector<int> subset;\n            for (int i = 0; i < S.size(); i++) {\n                if (selected[i]) subset.push_back(S[i]);\n            }\n            result.push_back(subset);\n            return;\n        }\n        // 不选S[step]\n        selected[step] = false;\n        subsets(S, selected, step + 1, result);\n        // 选S[step]\n        selected[step] = true;\n        subsets(S, selected, step + 1, result);\n    }\n};\n\\end{Code}\n\n\n\\subsection{迭代}\n\n\n\\subsubsection{增量构造法}\n\\begin{Code}\n// LeetCode, Subsets\n// 迭代版，时间复杂度O(2^n)，空间复杂度O(1)\nclass Solution {\npublic:\n    vector<vector<int> > subsets(vector<int> &S) {\n        sort(S.begin(), S.end()); // 输出要求有序\n        vector<vector<int> > result(1);\n        for (auto elem : S) {\n            result.reserve(result.size() * 2);\n            auto half = result.begin() + result.size();\n            copy(result.begin(), half, back_inserter(result));\n            for_each(half, result.end(), [&elem](decltype(result[0]) &e){\n                e.push_back(elem);\n            });\n        }\n        return result;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{二进制法}\n本方法的前提是：集合的元素不超过int位数。用一个int整数表示位向量，第$i$位为1，则表示选择$S[i]$，为0则不选择。例如\\fn{S=\\{A,B,C,D\\}}，则\\fn{0110=6}表示子集\\fn{\\{B,C\\}}。\n\n这种方法最巧妙。因为它不仅能生成子集，还能方便的表示集合的并、交、差等集合运算。设两个集合的位向量分别为$B_1$和$B_2$，则$B_1\\cup B_2, B_1 \\cap B_2, B_1 \\triangle B_2$分别对应集合的并、交、对称差。\n\n二进制法，也可以看做是位向量法，只不过更加优化。\n\n\\begin{Code}\n// LeetCode, Subsets\n// 二进制法，时间复杂度O(2^n)，空间复杂度O(1)\nclass Solution {\npublic:\n    vector<vector<int> > subsets(vector<int> &S) {\n        sort(S.begin(), S.end()); // 输出要求有序\n        vector<vector<int> > result;\n        const size_t n = S.size();\n        vector<int> v;\n\n        for (size_t i = 0; i < 1 << n; i++) {\n            for (size_t j = 0; j < n; j++) {\n                if (i & 1 << j) v.push_back(S[j]);\n            }\n            result.push_back(v);\n            v.clear();\n        }\n        return result;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Subsets II，见 \\S \\ref{sec:subsets-ii}\n\\myenddot\n\n\n\\section{Subsets II} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:subsets-ii}\n\n\n\\subsubsection{描述}\nGiven a collection of integers that might contain duplicates, $S$, return all possible subsets.\n\nNote:\n\nElements in a subset must be in non-descending order.\nThe solution set must not contain duplicate subsets.\nFor example,\nIf \\fn{S = [1,2,2]}, a solution is:\n\\begin{Code}\n[\n  [2],\n  [1],\n  [1,2,2],\n  [2,2],\n  [1,2],\n  []\n]\n\\end{Code}\n\n\n\\subsubsection{分析}\n这题有重复元素，但本质上，跟上一题很类似，上一题中元素没有重复，相当于每个元素只能选0或1次，这里扩充到了每个元素可以选0到若干次而已。\n\n\n\\subsection{递归}\n\n\n\\subsubsection{增量构造法}\n\\begin{Code}\n// LeetCode, Subsets II\n// 增量构造法，版本1，时间复杂度O(2^n)，空间复杂度O(n)\nclass Solution {\npublic:\n    vector<vector<int> > subsetsWithDup(vector<int> &S) {\n        sort(S.begin(), S.end());  // 必须排序\n\n        vector<vector<int> > result;\n        vector<int> path;\n\n        dfs(S, S.begin(), path, result);\n        return result;\n    }\n\nprivate:\n    static void dfs(const vector<int> &S, vector<int>::iterator start,\n            vector<int> &path, vector<vector<int> > &result) {\n        result.push_back(path);\n\n        for (auto i = start; i < S.end(); i++) {\n            if (i != start && *i == *(i-1)) continue;\n            path.push_back(*i);\n            dfs(S, i + 1, path, result);\n            path.pop_back();\n        }\n    }\n};\n\\end{Code}\n\n\\begin{Code}\n// LeetCode, Subsets II\n// 增量构造法，版本2，时间复杂度O(2^n)，空间复杂度O(n)\nclass Solution {\npublic:\n    vector<vector<int> > subsetsWithDup(vector<int> &S) {\n        vector<vector<int> > result;\n        sort(S.begin(), S.end()); // 必须排序\n\n        unordered_map<int, int> count_map; // 记录每个元素的出现次数\n        for_each(S.begin(), S.end(), [&count_map](int e) {\n            if (count_map.find(e) != count_map.end())\n                count_map[e]++;\n            else\n                count_map[e] = 1;\n        });\n\n        // 将map里的pair拷贝到一个vector里\n        vector<pair<int, int> > elems;\n        for_each(count_map.begin(), count_map.end(),\n                [&elems](const pair<int, int> &e) {\n                    elems.push_back(e);\n                });\n        sort(elems.begin(), elems.end());\n        vector<int> path; // 中间结果\n\n        subsets(elems, 0, path, result);\n        return result;\n    }\n\nprivate:\n    static void subsets(const vector<pair<int, int> > &elems,\n            size_t step, vector<int> &path, vector<vector<int> > &result) {\n        if (step == elems.size()) {\n            result.push_back(path);\n            return;\n        }\n\n        for (int i = 0; i <= elems[step].second; i++) {\n            for (int j = 0; j < i; ++j) {\n                path.push_back(elems[step].first);\n            }\n            subsets(elems, step + 1, path, result);\n            for (int j = 0; j < i; ++j) {\n                path.pop_back();\n            }\n        }\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{位向量法}\n\\begin{Code}\n// LeetCode, Subsets II\n// 位向量法，时间复杂度O(2^n)，空间复杂度O(n)\nclass Solution {\npublic:\n    vector<vector<int> > subsetsWithDup(vector<int> &S) {\n        vector<vector<int> > result; // 必须排序\n        sort(S.begin(), S.end());\n        vector<int> count(S.back() - S.front() + 1, 0);\n        // 计算所有元素的个数\n        for (auto i : S) {\n            count[i - S[0]]++;\n        }\n\n        // 每个元素选择了多少个\n        vector<int> selected(S.back() - S.front() + 1, -1);\n\n        subsets(S, count, selected, 0, result);\n        return result;\n    }\n\nprivate:\n    static void subsets(const vector<int> &S, vector<int> &count,\n            vector<int> &selected, size_t step, vector<vector<int> > &result) {\n        if (step == count.size()) {\n            vector<int> subset;\n            for(size_t i = 0; i < selected.size(); i++) {\n                for (int j = 0; j < selected[i]; j++) {\n                    subset.push_back(i+S[0]);\n                }\n            }\n            result.push_back(subset);\n            return;\n        }\n\n        for (int i = 0; i <= count[step]; i++) {\n            selected[step] = i;\n            subsets(S, count, selected, step + 1, result);\n        }\n    }\n};\n\\end{Code}\n\n\n\\subsection{迭代}\n\n\n\\subsubsection{增量构造法}\n\\begin{Code}\n// LeetCode, Subsets II\n// 增量构造法\n// 时间复杂度O(2^n)，空间复杂度O(1)\nclass Solution {\npublic:\n    vector<vector<int> > subsetsWithDup(vector<int> &S) {\n        sort(S.begin(), S.end()); // 必须排序\n        vector<vector<int> > result(1);\n\n        size_t previous_size = 0;\n        for (size_t i = 0; i < S.size(); ++i) {\n            const size_t size = result.size();\n            for (size_t j = 0; j < size; ++j) {\n                if (i == 0 || S[i] != S[i-1] || j >= previous_size) {\n                    result.push_back(result[j]);\n                    result.back().push_back(S[i]);\n                }\n            }\n            previous_size = size;\n        }\n        return result;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{二进制法}\n\\begin{Code}\n// LeetCode, Subsets II\n// 二进制法，时间复杂度O(2^n)，空间复杂度O(1)\nclass Solution {\npublic:\n    vector<vector<int> > subsetsWithDup(vector<int> &S) {\n        sort(S.begin(), S.end()); // 必须排序\n        // 用 set 去重，不能用 unordered_set，因为输出要求有序\n        set<vector<int> > result;\n        const size_t n = S.size();\n        vector<int> v;\n\n        for (size_t i = 0; i < 1U << n; ++i) {\n            for (size_t j = 0; j < n; ++j) {\n                if (i & 1 << j)\n                    v.push_back(S[j]);\n            }\n            result.insert(v);\n            v.clear();\n        }\n        vector<vector<int> > real_result;\n        copy(result.begin(), result.end(), back_inserter(real_result));\n        return real_result;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Subsets，见 \\S \\ref{sec:subsets}\n\\myenddot\n\n\n\\section{Permutations} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:permutations}\n\n\n\\subsubsection{描述}\nGiven a collection of numbers, return all possible permutations.\n\nFor example,\n\\fn{[1,2,3]} have the following permutations:\n\\fn{[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2]}, and \\fn{[3,2,1]}.\n\n\n\\subsection{next_permutation()}\n偷懒的做法，可以直接使用\\fn{std::next_permutation()}。如果是在OJ网站上，可以用这个API偷个懒；如果是在面试中，面试官肯定会让你重新实现。\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Permutations\n// 时间复杂度O(n!)，空间复杂度O(1)\nclass Solution {\npublic:\n    vector<vector<int> > permute(vector<int> &num) {\n        vector<vector<int> > result;\n        sort(num.begin(), num.end());\n\n        do {\n            result.push_back(num);\n        } while(next_permutation(num.begin(), num.end()));\n        return result;\n    }\n};\n\\end{Code}\n\n\n\\subsection{重新实现next_permutation()}\n见第 \\S \\ref{sec:next-permutation} 节。\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Permutations\n// 重新实现 next_permutation()\n// 时间复杂度O(n!)，空间复杂度O(1)\nclass Solution {\npublic:\n    vector<vector<int> > permute(vector<int> &num) {\n        vector<vector<int> > result;\n        sort(num.begin(), num.end());\n\n        do {\n            result.push_back(num);\n        // 调用的是 2.1.12 节的 next_permutation()\n        // 而不是 std::next_permutation()\n        } while(next_permutation(num.begin(), num.end()));\n        return result;\n    }\n};\n\\end{Code}\n\n\n\\subsection{递归}\n本题是求路径本身，求所有解，函数参数需要标记当前走到了哪步，还需要中间结果的引用，最终结果的引用。\n\n扩展节点，每次从左到右，选一个没有出现过的元素。\n\n本题不需要判重，因为状态装换图是一颗有层次的树。收敛条件是当前走到了最后一个元素。\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Permutations\n// 深搜，增量构造法\n// 时间复杂度O(n!)，空间复杂度O(n)\nclass Solution {\npublic:\n    vector<vector<int> > permute(vector<int>& num) {\n        sort(num.begin(), num.end());\n\n        vector<vector<int>> result;\n        vector<int> path;  // 中间结果\n\n        dfs(num, path, result);\n        return result;\n    }\nprivate:\n    void dfs(const vector<int>& num, vector<int> &path,\n            vector<vector<int> > &result) {\n        if (path.size() == num.size()) {  // 收敛条件\n            result.push_back(path);\n            return;\n        }\n\n        // 扩展状态\n        for (auto i : num) {\n            // 查找 i 是否在path 中出现过\n            auto pos = find(path.begin(), path.end(), i);\n\n            if (pos == path.end()) {\n                path.push_back(i);\n                dfs(num, path, result);\n                path.pop_back();\n            }\n        }\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Next Permutation, 见 \\S \\ref{sec:next-permutation}\n\\item Permutation Sequence, 见 \\S \\ref{sec:permutation-sequence}\n\\item Permutations II, 见 \\S \\ref{sec:permutations-ii}\n\\item Combinations, 见 \\S \\ref{sec:combinations}\n\\myenddot\n\n\n\\section{Permutations II} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:permutations-ii}\n\n\n\\subsubsection{描述}\nGiven a collection of numbers that might contain duplicates, return all possible unique permutations.\n\nFor example,\n\\fn{[1,1,2]} have the following unique permutations:\n\\fn{[1,1,2], [1,2,1]}, and \\fn{[2,1,1]}.\n\n\n\\subsection{next_permutation()}\n直接使用\\fn{std::next_permutation()}，代码与上一题相同。\n\n\n\\subsection{重新实现next_permutation()}\n重新实现\\fn{std::next_permutation()}，代码与上一题相同。\n\n\n\\subsection{递归}\n递归函数\\fn{permute()}的参数\\fn{p}，是中间结果，它的长度又能标记当前走到了哪一步，用于判断收敛条件。\n\n扩展节点，每次从小到大，选一个没有被用光的元素，直到所有元素被用光。\n\n本题不需要判重，因为状态装换图是一颗有层次的树。\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Permutations II\n// 深搜，时间复杂度O(n!)，空间复杂度O(n)\nclass Solution {\npublic:\n    vector<vector<int> > permuteUnique(vector<int>& num) {\n        sort(num.begin(), num.end());\n\n        unordered_map<int, int> count_map; // 记录每个元素的出现次数\n        for_each(num.begin(), num.end(), [&count_map](int e) {\n            if (count_map.find(e) != count_map.end())\n                count_map[e]++;\n            else\n                count_map[e] = 1;\n        });\n\n        // 将map里的pair拷贝到一个vector里\n        vector<pair<int, int> > elems;\n        for_each(count_map.begin(), count_map.end(),\n                [&elems](const pair<int, int> &e) {\n                    elems.push_back(e);\n                });\n\n        vector<vector<int>> result; // 最终结果\n        vector<int> p;  // 中间结果\n\n        n = num.size();\n        permute(elems.begin(), elems.end(), p, result);\n        return result;\n    }\n\nprivate:\n    size_t n;\n    typedef vector<pair<int, int> >::const_iterator Iter;\n\n    void permute(Iter first, Iter last, vector<int> &p,\n            vector<vector<int> > &result) {\n        if (n == p.size()) {  // 收敛条件\n            result.push_back(p);\n        }\n\n        // 扩展状态\n        for (auto i = first; i != last; i++) {\n            int count = 0; // 统计 *i 在p中出现过多少次\n            for (auto j = p.begin(); j != p.end(); j++) {\n                if (i->first == *j) {\n                    count ++;\n                }\n            }\n            if (count < i->second) {\n                p.push_back(i->first);\n                permute(first, last, p, result);\n                p.pop_back(); // 撤销动作，返回上一层\n            }\n        }\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Next Permutation, 见 \\S \\ref{sec:next-permutation}\n\\item Permutation Sequence, 见 \\S \\ref{sec:permutation-sequence}\n\\item Permutations, 见 \\S \\ref{sec:permutations}\n\\item Combinations, 见 \\S \\ref{sec:combinations}\n\\myenddot\n\n\n\\section{Combinations} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:combinations}\n\n\n\\subsubsection{描述}\nGiven two integers $n$ and $k$, return all possible combinations of $k$ numbers out of $1 ... n$.\n\nFor example,\nIf $n = 4$ and $k = 2$, a solution is:\n\\begin{Code}\n[\n  [2,4],\n  [3,4],\n  [2,3],\n  [1,2],\n  [1,3],\n  [1,4],\n]\n\\end{Code}\n\n\n\\subsection{递归}\n\\begin{Code}\n// LeetCode, Combinations\n// 深搜，递归\n// 时间复杂度O(n!)，空间复杂度O(n)\nclass Solution {\npublic:\n    vector<vector<int> > combine(int n, int k) {\n        vector<vector<int> > result;\n        vector<int> path;\n        dfs(n, k, 1, 0, path, result);\n        return result;\n    }\nprivate:\n    // start，开始的数, cur，已经选择的数目\n    static void dfs(int n, int k, int start, int cur,\n            vector<int> &path, vector<vector<int> > &result) {\n        if (cur == k) {\n            result.push_back(path);\n        }\n        for (int i = start; i <= n; ++i) {\n            path.push_back(i);\n            dfs(n, k, i + 1, cur + 1, path, result);\n            path.pop_back();\n        }\n    }\n};\n\\end{Code}\n\n\n\\subsection{迭代}\n\\begin{Code}\n// LeetCode, Combinations\n// use prev_permutation()\n// 时间复杂度O((n-k)!)，空间复杂度O(n)\nclass Solution {\npublic:\n    vector<vector<int> > combine(int n, int k) {\n        vector<int> values(n);\n        iota(values.begin(), values.end(), 1);\n\n        vector<bool> select(n, false);\n        fill_n(select.begin(), k, true);\n\n        vector<vector<int> > result;\n        do{\n            vector<int> one(k);\n            for (int i = 0, index = 0; i < n; ++i)\n                if (select[i])\n                    one[index++] = values[i];\n            result.push_back(one);\n        } while(prev_permutation(select.begin(), select.end()));\n        return result;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Next Permutation, 见 \\S \\ref{sec:next-permutation}\n\\item Permutation Sequence, 见 \\S \\ref{sec:permutation-sequence}\n\\item Permutations, 见 \\S \\ref{sec:permutations}\n\\item Permutations II, 见 \\S \\ref{sec:permutations-ii}\n\\myenddot\n\n\n\\section{Letter Combinations of a Phone Number } %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:letter-combinations-of-a-phone-number }\n\n\n\\subsubsection{描述}\nGiven a digit string, return all possible letter combinations that the number could represent.\n\nA mapping of digit to letters (just like on the telephone buttons) is given below.\n\n\\begin{center}\n\\includegraphics[width=150pt]{phone-keyboard.png}\\\\\n\\figcaption{Phone Keyboard}\\label{fig:phone-keyboard}\n\\end{center}\n\n\\textbf{Input:}Digit string \\code{\"23\"}\n\n\\textbf{Output:} \\code{[\"ad\", \"ae\", \"af\", \"bd\", \"be\", \"bf\", \"cd\", \"ce\", \"cf\"]}.\n\n\\textbf{Note:}\nAlthough the above answer is in lexicographical order, your answer could be in any order you want.\n\n\n\\subsubsection{分析}\n无\n\n\n\\subsection{递归}\n\\begin{Code}\n// LeetCode, Letter Combinations of a Phone Number\n// 时间复杂度O(3^n)，空间复杂度O(n)\nclass Solution {\npublic:\n    const vector<string> keyboard { \" \", \"\", \"abc\", \"def\", // '0','1','2',...\n            \"ghi\", \"jkl\", \"mno\", \"pqrs\", \"tuv\", \"wxyz\" };\n\n    vector<string> letterCombinations (const string &digits) {\n        vector<string> result;\n        if (digits.empty()) return result;\n        dfs(digits, 0, \"\", result);\n        return result;\n    }\n\n    void dfs(const string &digits, size_t cur, string path,\n            vector<string> &result) {\n        if (cur == digits.size()) {\n            result.push_back(path);\n            return;\n        }\n        for (auto c : keyboard[digits[cur] - '0']) {\n            dfs(digits, cur + 1, path + c, result);\n        }\n    }\n};\n\\end{Code}\n\n\n\\subsection{迭代}\n\\begin{Code}\n// LeetCode, Letter Combinations of a Phone Number\n// 时间复杂度O(3^n)，空间复杂度O(1)\nclass Solution {\npublic:\n    const vector<string> keyboard { \" \", \"\", \"abc\", \"def\", // '0','1','2',...\n            \"ghi\", \"jkl\", \"mno\", \"pqrs\", \"tuv\", \"wxyz\" };\n\n    vector<string> letterCombinations (const string &digits) {\n        if (digits.empty()) return vector<string>();\n        vector<string> result(1, \"\");\n        for (auto d : digits) {\n            const size_t n = result.size();\n            const size_t m = keyboard[d - '0'].size();\n\n            result.resize(n * m);\n            for (size_t i = 0; i < m; ++i)\n                copy(result.begin(), result.begin() + n, result.begin() + n * i);\n\n            for (size_t i = 0; i < m; ++i) {\n                auto begin = result.begin();\n                for_each(begin + n * i, begin + n * (i+1), [&](string &s) {\n                    s += keyboard[d - '0'][i];\n                });\n            }\n        }\n        return result;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item 无\n\\myenddot\n"
  },
  {
    "path": "C++/chapDFS.tex",
    "content": "\\chapter{深度优先搜索}\n\n\n\\section{Palindrome Partitioning} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:palindrome-partitioning}\n\n\n\\subsubsection{描述}\nGiven a string s, partition s such that every substring of the partition is a palindrome.\n\nReturn all possible palindrome partitioning of s.\n\nFor example, given \\code{s = \"aab\"},\nReturn\n\\begin{Code}\n  [\n    [\"aa\",\"b\"],\n    [\"a\",\"a\",\"b\"]\n  ]\n\\end{Code}\n\n\n\\subsubsection{分析}\n在每一步都可以判断中间结果是否为合法结果，用回溯法。\n\n一个长度为n的字符串，有$n-1$个地方可以砍断，每个地方可断可不断，因此复杂度为$O(2^{n-1})$\n\n\n\\subsubsection{深搜1}\n\\begin{Code}\n//LeetCode, Palindrome Partitioning\n// 时间复杂度O(2^n)，空间复杂度O(n)\nclass Solution {\npublic:\n    vector<vector<string>> partition(string s) {\n        vector<vector<string>> result;\n        vector<string> path;  // 一个partition方案\n        dfs(s, path, result, 0, 1);\n        return result;\n    }\n\n    // prev 表示前一个隔板, start 表示当前隔板\n    void dfs(string &s, vector<string>& path,\n            vector<vector<string>> &result, size_t prev, size_t start) {\n        if (start == s.size()) { // 最后一个隔板\n            if (isPalindrome(s, prev, start - 1)) { // 必须使用\n                path.push_back(s.substr(prev, start - prev));\n                result.push_back(path);\n                path.pop_back();\n            }\n            return;\n        }\n        // 不断开\n        dfs(s, path, result, prev, start + 1);\n        // 如果[prev, start-1] 是回文，则可以断开，也可以不断开（上一行已经做了）\n        if (isPalindrome(s, prev, start - 1)) {\n            // 断开\n            path.push_back(s.substr(prev, start - prev));\n            dfs(s, path, result, start, start + 1);\n            path.pop_back();\n        }\n    }\n\n    bool isPalindrome(const string &s, int start, int end) {\n        while (start < end && s[start] == s[end]) {\n            ++start;\n            --end;\n        }\n        return start >= end;\n    }\n};\n\\end{Code}\n\n\\subsubsection{深搜2}\n另一种写法，更加简洁。这种写法也在 Combination Sum, Combination Sum II 中出现过。\n\\begin{Code}\n//LeetCode, Palindrome Partitioning\n// 时间复杂度O(2^n)，空间复杂度O(n)\nclass Solution {\npublic:\n    vector<vector<string>> partition(string s) {\n        vector<vector<string>> result;\n        vector<string> path;  // 一个partition方案\n        DFS(s, path, result, 0);\n        return result;\n    }\n    // 搜索必须以s[start]开头的partition方案\n    void DFS(string &s, vector<string>& path,\n            vector<vector<string>> &result, int start) {\n        if (start == s.size()) {\n            result.push_back(path);\n            return;\n        }\n        for (int i = start; i < s.size(); i++) {\n            if (isPalindrome(s, start, i)) { // 从i位置砍一刀\n                path.push_back(s.substr(start, i - start + 1));\n                DFS(s, path, result, i + 1);  // 继续往下砍\n                path.pop_back(); // 撤销上上行\n            }\n        }\n    }\n    bool isPalindrome(const string &s, int start, int end) {\n        while (start < end && s[start] == s[end]) {\n            ++start;\n            --end;\n        }\n        return start >= end;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{动规}\n\\begin{Code}\n// LeetCode, Palindrome Partitioning\n// 动规，时间复杂度O(n^2)，空间复杂度O(1)\nclass Solution {\npublic:\n    vector<vector<string> > partition(string s) {\n        const int n = s.size();\n        bool p[n][n]; // whether s[i,j] is palindrome\n        fill_n(&p[0][0], n * n, false);\n        for (int i = n - 1; i >= 0; --i)\n            for (int j = i; j < n; ++j)\n                p[i][j] = s[i] == s[j] && ((j - i < 2) || p[i + 1][j - 1]);\n\n        vector<vector<string> > sub_palins[n]; // sub palindromes of s[0,i]\n        for (int i = n - 1; i >= 0; --i) {\n            for (int j = i; j < n; ++j)\n                if (p[i][j]) {\n                    const string palindrome = s.substr(i, j - i + 1);\n                    if (j + 1 < n) {\n                        for (auto v : sub_palins[j + 1]) {\n                            v.insert(v.begin(), palindrome);\n                            sub_palins[i].push_back(v);\n                        }\n                    } else {\n                        sub_palins[i].push_back(vector<string> { palindrome });\n                    }\n                }\n        }\n        return sub_palins[0];\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\n\\begindot\n\\item Palindrome Partitioning II，见 \\S \\ref{sec:palindrome-partitioning-ii}\n\\myenddot\n\n\n\\section{Unique Paths} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:unique-paths}\n\n\n\\subsubsection{描述}\nA robot is located at the top-left corner of a $m \\times n$ grid (marked 'Start' in the diagram below).\n\nThe robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).\n\nHow many possible unique paths are there?\n\n\\begin{center}\n\\includegraphics[width=200pt]{robot-maze.png}\\\\\n\\figcaption{Above is a $3 \\times 7$ grid. How many possible unique paths are there?}\\label{fig:unique-paths}\n\\end{center}\n\n\\textbf{Note}: $m$ and $n$ will be at most 100.\n\n\n\\subsection{深搜}\n深搜，小集合可以过，大集合会超时\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Unique Paths\n// 深搜，小集合可以过，大集合会超时\n// 时间复杂度O(n^4)，空间复杂度O(n)\nclass Solution {\npublic:\n    int uniquePaths(int m, int n) {\n        if (m < 1 || n < 1) return 0; // 终止条件\n\n        if (m == 1 && n == 1) return 1; // 收敛条件\n\n        return uniquePaths(m - 1, n) + uniquePaths(m, n - 1);\n    }\n};\n\\end{Code}\n\n\n\\subsection{备忘录法}\n给前面的深搜，加个缓存，就可以过大集合了。即备忘录法。\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Unique Paths\n// 深搜 + 缓存，即备忘录法\n// 时间复杂度O(n^2)，空间复杂度O(n^2)\nclass Solution {\npublic:\n    int uniquePaths(int m, int n) {\n        // f[x][y] 表示 从(0,0)到(x,y)的路径条数\n        f = vector<vector<int> >(m, vector<int>(n, 0));\n        f[0][0] = 1;\n        return dfs(m - 1, n - 1);\n    }\nprivate:\n    vector<vector<int> > f;  // 缓存\n\n    int dfs(int x, int y) {\n        if (x < 0 || y < 0) return 0; // 数据非法，终止条件\n\n        if (x == 0 && y == 0) return f[0][0]; // 回到起点，收敛条件\n\n        if (f[x][y] > 0) {\n            return f[x][y];\n        } else {\n            return f[x][y] = dfs(x - 1, y) +  dfs(x, y - 1);\n        }\n    }\n};\n\\end{Code}\n\n\n\\subsection{动规}\n既然可以用备忘录法自顶向下解决，也一定可以用动规自底向上解决。\n\n设状态为\\fn{f[i][j]}，表示从起点$(1,1)$到达$(i,j)$的路线条数，则状态转移方程为：\n\\begin{Code}\nf[i][j]=f[i-1][j]+f[i][j-1]\n\\end{Code}\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Unique Paths\n// 动规，滚动数组\n// 时间复杂度O(n^2)，空间复杂度O(n)\nclass Solution {\npublic:\n    int uniquePaths(int m, int n) {\n        vector<int> f(n, 0);\n        f[0] = 1;\n        for (int i = 0; i < m; i++) {\n            for (int j = 1; j < n; j++) {\n                // 左边的f[j]，表示更新后的f[j]，与公式中的f[i][j]对应\n                // 右边的f[j]，表示老的f[j]，与公式中的f[i-1][j]对应\n                f[j] = f[j] + f[j - 1];\n            }\n        }\n        return f[n - 1];\n    }\n};\n\\end{Code}\n\n\n\\subsection{数学公式}\n一个$m$行，$n$列的矩阵，机器人从左上走到右下总共需要的步数是$m+n-2$，其中向下走的步数是$m-1$，因此问题变成了在$m+n-2$个操作中，选择$m–1$个时间点向下走，选择方式有多少种。即 $C_{m+n-2}^{m-1}$ 。\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Unique Paths\n// 数学公式\nclass Solution {\npublic:\n    typedef long long int64_t;\n    // 求阶乘, n!/(start-1)!，即 n*(n-1)...start，要求 n >= 1\n    static int64_t factor(int n, int start = 1) {\n        int64_t  ret = 1;\n        for(int i = start; i <= n; ++i)\n            ret *= i;\n        return ret;\n    }\n    // 求组合数 C_n^k\n    static int64_t combination(int n, int k) {\n        // 常数优化\n        if (k == 0) return 1;\n        if (k == 1) return n;\n\n        int64_t ret = factor(n, k+1);\n        ret /= factor(n - k);\n        return ret;\n    }\n\n    int uniquePaths(int m, int n) {\n        // max 可以防止n和k差距过大，从而防止combination()溢出\n        return combination(m+n-2, max(m-1, n-1));\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Unique Paths II，见 \\S \\ref{sec:unique-paths-ii}\n\\item Minimum Path Sum, 见 \\S \\ref{sec:minimum-path-sum}\n\\myenddot\n\n\n\\section{Unique Paths II} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:unique-paths-ii}\n\n\n\\subsubsection{描述}\nFollow up for \"Unique Paths\":\n\nNow consider if some obstacles are added to the grids. How many unique paths would there be?\n\nAn obstacle and empty space is marked as 1 and 0 respectively in the grid.\n\nFor example,\n\nThere is one obstacle in the middle of a $3 \\times 3$ grid as illustrated below.\n\\begin{Code}\n[\n  [0,0,0],\n  [0,1,0],\n  [0,0,0]\n]\n\\end{Code}\n\nThe total number of unique paths is 2.\n\nNote: $m$ and $n$ will be at most 100.\n\n\n\\subsection{备忘录法}\n在上一题的基础上改一下即可。相比动规，简单得多。\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Unique Paths II\n// 深搜 + 缓存，即备忘录法\nclass Solution {\npublic:\n    int uniquePathsWithObstacles(const vector<vector<int> >& obstacleGrid) {\n        const int m = obstacleGrid.size();\n        const int n = obstacleGrid[0].size();\n        if (obstacleGrid[0][0] || obstacleGrid[m - 1][n - 1]) return 0;\n\n        f = vector<vector<int> >(m, vector<int>(n, 0));\n        f[0][0] = obstacleGrid[0][0] ? 0 : 1;\n        return dfs(obstacleGrid, m - 1, n - 1);\n    }\nprivate:\n    vector<vector<int> > f;  // 缓存\n\n    // @return 从 (0, 0) 到 (x, y) 的路径总数\n    int dfs(const vector<vector<int> >& obstacleGrid,\n            int x, int y) {\n        if (x < 0 || y < 0) return 0; // 数据非法，终止条件\n\n        // (x,y)是障碍\n        if (obstacleGrid[x][y]) return 0;\n\n        if (x == 0 and y == 0) return f[0][0]; // 回到起点，收敛条件\n\n        if (f[x][y] > 0) {\n            return f[x][y];\n        } else {\n            return f[x][y] = dfs(obstacleGrid, x - 1, y) + \n                dfs(obstacleGrid, x, y - 1);\n        }\n    }\n};\n\\end{Code}\n\n\n\\subsection{动规}\n与上一题类似，但要特别注意第一列的障碍。在上一题中，第一列全部是1，但是在这一题中不同，第一列如果某一行有障碍物，那么后面的行全为0。\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Unique Paths II\n// 动规，滚动数组\n// 时间复杂度O(n^2)，空间复杂度O(n)\nclass Solution {\npublic:\n    int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {\n        const int m = obstacleGrid.size();\n        const int n = obstacleGrid[0].size();\n        if (obstacleGrid[0][0] || obstacleGrid[m-1][n-1]) return 0;\n\n        vector<int> f(n, 0);\n        f[0] = obstacleGrid[0][0] ? 0 : 1;\n\n        for (int i = 0; i < m; i++) {\n            f[0] = f[0] == 0 ? 0 : (obstacleGrid[i][0] ? 0 : 1);\n            for (int j = 1; j < n; j++)\n                f[j] = obstacleGrid[i][j] ? 0 : (f[j] + f[j - 1]);\n        }\n\n        return f[n - 1];\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Unique Paths，见 \\S \\ref{sec:unique-paths}\n\\item Minimum Path Sum, 见 \\S \\ref{sec:minimum-path-sum}\n\\myenddot\n\n\n\\section{N-Queens} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:n-queens}\n\n\n\\subsubsection{描述}\nThe \\emph{n-queens puzzle} is the problem of placing n queens on an $n \\times n$ chessboard such that no two queens attack each other.\n\n\\begin{center}\n\\includegraphics{8-queens.png}\\\\\n\\figcaption{Eight Queens}\\label{fig:8-queens}\n\\end{center}\n\nGiven an integer $n$, return all distinct solutions to the n-queens puzzle.\n\nEach solution contains a distinct board configuration of the n-queens' placement, where \\fn{'Q'} and \\fn{'.'} both indicate a queen and an empty space respectively.\n\nFor example,\nThere exist two distinct solutions to the 4-queens puzzle:\n\\begin{Code}\n[\n [\".Q..\",  // Solution 1\n  \"...Q\",\n  \"Q...\",\n  \"..Q.\"],\n\n [\"..Q.\",  // Solution 2\n  \"Q...\",\n  \"...Q\",\n  \".Q..\"]\n]\n\\end{Code}\n\n\n\\subsubsection{分析}\n\n经典的深搜题。\n\n设置一个数组 \\fn{vector<int> C(n, 0)}, \\fn{C[i]} 表示第i行皇后所在的列编号，即在位置 (i, C[i]) 上放了一个皇后，这样用一个一维数组，就能记录整个棋盘。\n\n\n\\subsubsection{代码1}\n\\begin{Code}\n// LeetCode, N-Queens\n// 深搜+剪枝\n// 时间复杂度O(n!*n)，空间复杂度O(n)\nclass Solution {\npublic:\n    vector<vector<string> > solveNQueens(int n) {\n        vector<vector<string> > result;\n        vector<int> C(n, -1);  // C[i]表示第i行皇后所在的列编号\n        dfs(C, result, 0);\n        return result;\n    }\nprivate:\n    void dfs(vector<int> &C, vector<vector<string> > &result, int row) {\n        const int N = C.size();\n        if (row == N) { // 终止条件，也是收敛条件，意味着找到了一个可行解\n            vector<string> solution;\n            for (int i = 0; i < N; ++i) {\n                string s(N, '.');\n                for (int j = 0; j < N; ++j) {\n                    if (j == C[i]) s[j] = 'Q';\n                }\n                solution.push_back(s);\n            }\n            result.push_back(solution);\n            return;\n        }\n\n        for (int j = 0; j < N; ++j) {  // 扩展状态，一列一列的试\n            const bool ok = isValid(C, row, j);\n            if (!ok) continue;  // 剪枝，如果非法，继续尝试下一列\n            // 执行扩展动作\n            C[row] = j;\n            dfs(C, result, row + 1);\n            // 撤销动作\n            // C[row] = -1;\n        }\n    }\n    \n    /**\n     * 能否在 (row, col) 位置放一个皇后.\n     *\n     * @param C 棋局\n     * @param row 当前正在处理的行，前面的行都已经放了皇后了\n     * @param col 当前列\n     * @return 能否放一个皇后\n     */\n    bool isValid(const vector<int> &C, int row, int col) {\n        for (int i = 0; i < row; ++i) {\n            // 在同一列\n            if (C[i] == col) return false;\n            // 在同一对角线上\n            if (abs(i - row) == abs(C[i] - col)) return false;\n        }\n        return true;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{代码2}\n\\begin{Code}\n// LeetCode, N-Queens\n// 深搜+剪枝\n// 时间复杂度O(n!)，空间复杂度O(n)\nclass Solution {\npublic:\n    vector<vector<string> > solveNQueens(int n) {\n        this->columns = vector<bool>(n, false);\n        this->main_diag = vector<bool>(2 * n - 1, false);\n        this->anti_diag = vector<bool>(2 * n - 1, false);\n\n        vector<vector<string> > result;\n        vector<int> C(n, -1);  // C[i]表示第i行皇后所在的列编号\n        dfs(C, result, 0);\n        return result;\n    }\nprivate:\n    // 这三个变量用于剪枝\n    vector<bool> columns;  // 表示已经放置的皇后占据了哪些列\n    vector<bool> main_diag;  // 占据了哪些主对角线\n    vector<bool> anti_diag;  // 占据了哪些副对角线\n\n    void dfs(vector<int> &C, vector<vector<string> > &result, int row) {\n        const int N = C.size();\n        if (row == N) { // 终止条件，也是收敛条件，意味着找到了一个可行解\n            vector<string> solution;\n            for (int i = 0; i < N; ++i) {\n                string s(N, '.');\n                for (int j = 0; j < N; ++j) {\n                    if (j == C[i]) s[j] = 'Q';\n                }\n                solution.push_back(s);\n            }\n            result.push_back(solution);\n            return;\n        }\n\n        for (int j = 0; j < N; ++j) {  // 扩展状态，一列一列的试\n            const bool ok = !columns[j] && !main_diag[row - j + N - 1]  &&\n                    !anti_diag[row + j];\n            if (!ok) continue;  // 剪枝，如果非法，继续尝试下一列\n            // 执行扩展动作\n            C[row] = j;\n            columns[j] = main_diag[row - j + N - 1] = anti_diag[row + j] = true;\n            dfs(C, result, row + 1);\n            // 撤销动作\n            // C[row] = -1;\n            columns[j] = main_diag[row - j + N - 1] = anti_diag[row + j] = false;\n        }\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item N-Queens II，见 \\S \\ref{sec:n-queens-ii}\n\\myenddot\n\n\n\\section{N-Queens II} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:n-queens-ii}\n\n\n\\subsubsection{描述}\nFollow up for N-Queens problem.\n\nNow, instead outputting board configurations, return the total number of distinct solutions.\n\n\n\\subsubsection{分析}\n只需要输出解的个数，不需要输出所有解，代码要比上一题简化很多。设一个全局计数器，每找到一个解就增1。\n\n\n\\subsubsection{代码1}\n\\begin{Code}\n// LeetCode, N-Queens II\n// 深搜+剪枝\n// 时间复杂度O(n!*n)，空间复杂度O(n)\nclass Solution {\npublic:\n    int totalNQueens(int n) {\n        this->count = 0;\n\n        vector<int> C(n, 0);  // C[i]表示第i行皇后所在的列编号\n        dfs(C, 0);\n        return this->count;\n    }\nprivate:\n    int count; // 解的个数\n\n    void dfs(vector<int> &C, int row) {\n        const int N = C.size();\n        if (row == N) { // 终止条件，也是收敛条件，意味着找到了一个可行解\n            ++this->count;\n            return;\n        }\n\n        for (int j = 0; j < N; ++j) {  // 扩展状态，一列一列的试\n            const bool ok = isValid(C, row, j);\n            if (!ok) continue;  // 剪枝：如果合法，继续递归\n            // 执行扩展动作\n            C[row] = j;\n            dfs(C, row + 1);\n            // 撤销动作\n            // C[row] = -1;\n        }\n    }\n    /**\n     * 能否在 (row, col) 位置放一个皇后.\n     *\n     * @param C 棋局\n     * @param row 当前正在处理的行，前面的行都已经放了皇后了\n     * @param col 当前列\n     * @return 能否放一个皇后\n     */\n    bool isValid(const vector<int> &C, int row, int col) {\n        for (int i = 0; i < row; ++i) {\n            // 在同一列\n            if (C[i] == col) return false;\n            // 在同一对角线上\n            if (abs(i - row) == abs(C[i] - col)) return false;\n        }\n        return true;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{代码2}\n\\begin{Code}\n// LeetCode, N-Queens II\n// 深搜+剪枝\n// 时间复杂度O(n!)，空间复杂度O(n)\nclass Solution {\npublic:\n    int totalNQueens(int n) {\n        this->count = 0;\n        this->columns = vector<bool>(n, false);\n        this->main_diag = vector<bool>(2 * n - 1, false);\n        this->anti_diag = vector<bool>(2 * n - 1, false);\n\n        vector<int> C(n, 0);  // C[i]表示第i行皇后所在的列编号\n        dfs(C, 0);\n        return this->count;\n    }\nprivate:\n    int count; // 解的个数\n    // 这三个变量用于剪枝\n    vector<bool> columns;  // 表示已经放置的皇后占据了哪些列\n    vector<bool> main_diag;  // 占据了哪些主对角线\n    vector<bool> anti_diag;  // 占据了哪些副对角线\n\n    void dfs(vector<int> &C, int row) {\n        const int N = C.size();\n        if (row == N) { // 终止条件，也是收敛条件，意味着找到了一个可行解\n            ++this->count;\n            return;\n        }\n\n        for (int j = 0; j < N; ++j) {  // 扩展状态，一列一列的试\n            const bool ok = !columns[j] &&\n                    !main_diag[row - j + N] &&\n                    !anti_diag[row + j];\n            if (!ok) continue;  // 剪枝：如果合法，继续递归\n            // 执行扩展动作\n            C[row] = j;\n            columns[j] = main_diag[row - j + N] =\n                    anti_diag[row + j] = true;\n            dfs(C, row + 1);\n            // 撤销动作\n            // C[row] = -1;\n            columns[j] = main_diag[row - j + N] =\n                    anti_diag[row + j] = false;\n        }\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item N-Queens，见 \\S \\ref{sec:n-queens}\n\\myenddot\n\n\n\\section{Restore IP Addresses} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:restore-ip-addresses}\n\n\n\\subsubsection{描述}\nGiven a string containing only digits, restore it by returning all possible valid IP address combinations.\n\nFor example:\nGiven \\code{\"25525511135\"},\n\nreturn \\code{[\"255.255.11.135\", \"255.255.111.35\"]}. (Order does not matter)\n\n\n\\subsubsection{分析}\n必须要走到底部才能判断解是否合法，深搜。\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Restore IP Addresses\n// 时间复杂度O(n^4)，空间复杂度O(n)\nclass Solution {\npublic:\n    vector<string> restoreIpAddresses(const string& s) {\n        vector<string> result;\n        vector<string> ip; // 存放中间结果\n        dfs(s, ip, result, 0);\n        return result;\n    }\n\n    /**\n     * @brief 解析字符串\n     * @param[in] s 字符串，输入数据\n     * @param[out] ip 存放中间结果\n     * @param[out] result 存放所有可能的IP地址\n     * @param[in] start 当前正在处理的 index\n     * @return 无\n     */\n    void dfs(string s, vector<string>& ip, vector<string> &result,\n            size_t start) {\n        if (ip.size() == 4 && start == s.size()) {  // 找到一个合法解\n            result.push_back(ip[0] + '.' + ip[1] + '.' + ip[2] + '.' + ip[3]);\n            return;\n        }\n\n        if (s.size() - start > (4 - ip.size()) * 3)\n            return;  // 剪枝\n        if (s.size() - start < (4 - ip.size()))\n            return;  // 剪枝\n\n        int num = 0;\n        for (size_t i = start; i < start + 3; i++) {\n            num = num * 10 + (s[i] - '0');\n\n            if (num < 0 || num > 255) continue;  // 剪枝\n            \n            ip.push_back(s.substr(start, i - start + 1));\n            dfs(s, ip, result, i + 1);\n            ip.pop_back();\n            \n            if (num == 0) break;  // 不允许前缀0，但允许单个0\n        }\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item 无\n\\myenddot\n\n\n\\section{Combination Sum} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:combination-sum}\n\n\n\\subsubsection{描述}\nGiven a set of candidate numbers ($C$) and a target number ($T$), find all unique combinations in $C$ where the candidate numbers sums to $T$.\n\nThe same repeated number may be chosen from $C$ \\emph{unlimited} number of times.\n\nNote:\n\\begindot\n\\item All numbers (including target) will be positive integers.\n\\item Elements in a combination ($a_1, a_2, ..., a_k$) must be in non-descending order. (ie, $a_1 \\leq a_2 \\leq ... \\leq a_k$).\n\\item The solution set must not contain duplicate combinations.\n\\myenddot\n\nFor example, given candidate set \\fn{2,3,6,7} and target \\fn{7}, \nA solution set is: \n\\begin{Code}\n[7] \n[2, 2, 3] \n\\end{Code}\n\n\n\\subsubsection{分析}\n无\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Combination Sum\n// 时间复杂度O(n!)，空间复杂度O(n)\nclass Solution {\npublic:\n    vector<vector<int> > combinationSum(vector<int> &nums, int target) {\n        sort(nums.begin(), nums.end());\n        vector<vector<int> > result; // 最终结果\n        vector<int> path; // 中间结果\n        dfs(nums, path, result, target, 0);\n        return result;\n    }\n\nprivate:\n    void dfs(vector<int>& nums, vector<int>& path, vector<vector<int> > &result,\n            int gap, int start) {\n        if (gap == 0) {  // 找到一个合法解\n            result.push_back(path);\n            return;\n        }\n        for (size_t i = start; i < nums.size(); i++) { // 扩展状态\n            if (gap < nums[i]) return; // 剪枝\n\n            path.push_back(nums[i]); // 执行扩展动作\n            dfs(nums, path, result, gap - nums[i], i);\n            path.pop_back();  // 撤销动作\n        }\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Combination Sum II ，见 \\S \\ref{sec:combination-sum-ii}\n\\myenddot\n\n\n\\section{Combination Sum II} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:combination-sum-ii}\n\n\n\\subsubsection{描述}\nGiven a collection of candidate numbers ($C$) and a target number ($T$), find all unique combinations in $C$ where the candidate numbers sums to $T$.\n\nEach number in $C$ may only be used \\emph{once} in the combination.\n\nNote:\n\\begindot\n\\item All numbers (including target) will be positive integers.\n\\item Elements in a combination ($a_1, a_2, ..., a_k$) must be in non-descending order. (ie, $a_1 > a_2 > ... > a_k$).\n\\item The solution set must not contain duplicate combinations.\n\\myenddot\n\nFor example, given candidate set \\fn{10,1,2,7,6,1,5} and target \\fn{8}, \nA solution set is: \n\\begin{Code}\n[1, 7] \n[1, 2, 5] \n[2, 6] \n[1, 1, 6]\n\\end{Code}\n\n\n\\subsubsection{分析}\n无\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Combination Sum II\n// 时间复杂度O(n!)，空间复杂度O(n)\nclass Solution {\npublic:\n    vector<vector<int> > combinationSum2(vector<int> &nums, int target) {\n        sort(nums.begin(), nums.end()); // 跟第 50 行配合，\n                                        // 确保每个元素最多只用一次\n        vector<vector<int> > result;\n        vector<int> path;\n        dfs(nums, path, result, target, 0);\n        return result;\n    }\nprivate:\n    // 使用nums[start, nums.size())之间的元素，能找到的所有可行解\n    static void dfs(const vector<int> &nums, vector<int> &path, \n            vector<vector<int> > &result, int gap, int start) {\n        if (gap == 0) {  //  找到一个合法解\n            result.push_back(path);\n            return;\n        }\n\n        int previous = -1;\n        for (size_t i = start; i < nums.size(); i++) {\n            // 如果上一轮循环已经使用了nums[i]，则本次循环就不能再选nums[i]，\n            // 确保nums[i]最多只用一次\n            if (previous == nums[i]) continue;\n\n            if (gap < nums[i]) return;  // 剪枝\n\n            previous = nums[i];\n\n            path.push_back(nums[i]);\n            dfs(nums, path, result, gap - nums[i], i + 1);\n            path.pop_back();  // 恢复环境\n        }\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Combination Sum ，见 \\S \\ref{sec:combination-sum}\n\\myenddot\n\n\n\\section{Generate Parentheses } %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:generate-parentheses}\n\n\n\\subsubsection{描述}\nGiven $n$ pairs of parentheses, write a function to generate all combinations of well-formed parentheses.\n\nFor example, given $n = 3$, a solution set is:\n\\begin{Code}\n\"((()))\", \"(()())\", \"(())()\", \"()(())\", \"()()()\"\n\\end{Code}\n\n\\subsubsection{分析}\n小括号串是一个递归结构，跟单链表、二叉树等递归结构一样，首先想到用递归。\n\n一步步构造字符串。当左括号出现次数$<n$时，就可以放置新的左括号。当右括号出现次数小于左括号出现次数时，就可以放置新的右括号。\n\n\n\\subsubsection{代码1}\n\\begin{Code}\n// LeetCode, Generate Parentheses\n// 时间复杂度O(TODO)，空间复杂度O(n)\nclass Solution {\npublic:\n    vector<string> generateParenthesis(int n) {\n        vector<string> result;\n        string path;\n        if (n > 0) generate(n, path, result, 0, 0);\n        return result;\n    }\n    // l 表示 ( 出现的次数, r 表示 ) 出现的次数\n    void generate(int n, string& path, vector<string> &result, int l, int r) {\n        if (l == n) {\n            string s(path);\n            result.push_back(s.append(n - r, ')'));\n            return;\n        }\n        \n        path.push_back('(');\n        generate(n, path, result, l + 1, r);\n        path.pop_back();\n\n        if (l > r) {\n            path.push_back(')');\n            generate(n, path, result, l, r + 1);\n            path.pop_back();\n        }\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{代码2}\n另一种递归写法，更加简洁。\n\\begin{Code}\n// LeetCode, Generate Parentheses\n// @author 连城 (http://weibo.com/lianchengzju)\nclass Solution {\npublic:\n    vector<string> generateParenthesis (int n) {\n        if (n == 0) return vector<string>(1, \"\");\n        if (n == 1) return vector<string> (1, \"()\");\n        vector<string> result;\n\n        for (int i = 0; i < n; ++i)\n            for (auto inner : generateParenthesis (i))\n                for (auto outer : generateParenthesis (n - 1 - i))\n                    result.push_back (\"(\" + inner + \")\" + outer);\n\n        return result;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Valid Parentheses, 见 \\S \\ref{sec:valid-parentheses}\n\\item Longest Valid Parentheses, 见 \\S \\ref{sec:longest-valid-parentheses}\n\\myenddot\n\n\n\\section{Sudoku Solver} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:sudoku-solver}\n\n\n\\subsubsection{描述}\nWrite a program to solve a Sudoku puzzle by filling the empty cells.\n\nEmpty cells are indicated by the character \\fn{'.'}.\n\nYou may assume that there will be only one unique solution.\n\n\\begin{center}\n\\includegraphics[width=150pt]{sudoku.png}\\\\\n\\figcaption{A sudoku puzzle...}\\label{fig:sudoku}\n\\end{center}\n\n\\begin{center}\n\\includegraphics[width=150pt]{sudoku-solution.png}\\\\\n\\figcaption{...and its solution numbers marked in red}\\label{fig:sudoku-solution}\n\\end{center}\n\n\n\\subsubsection{分析}\n无。\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Sudoku Solver\n// 时间复杂度O(9^4)，空间复杂度O(1)\nclass Solution {\npublic:\n    bool solveSudoku(vector<vector<char> > &board) {\n        for (int i = 0; i < 9; ++i)\n            for (int j = 0; j < 9; ++j) {\n                if (board[i][j] == '.') {\n                    for (int k = 0; k < 9; ++k) {\n                        board[i][j] = '1' + k;\n                        if (isValid(board, i, j) && solveSudoku(board))\n                            return true;\n                        board[i][j] = '.';\n                    }\n                    return false;\n                }\n            }\n        return true;\n    }\nprivate:\n    // 检查 (x, y) 是否合法\n    bool isValid(const vector<vector<char> > &board, int x, int y) {\n        int i, j;\n        for (i = 0; i < 9; i++) // 检查 y 列\n            if (i != x && board[i][y] == board[x][y])\n                return false;\n        for (j = 0; j < 9; j++) // 检查 x 行\n            if (j != y && board[x][j] == board[x][y])\n                return false;\n        for (i = 3 * (x / 3); i < 3 * (x / 3 + 1); i++)\n            for (j = 3 * (y / 3); j < 3 * (y / 3 + 1); j++)\n                if ((i != x || j != y) && board[i][j] == board[x][y])\n                    return false;\n        return true;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Valid Sudoku, 见 \\S \\ref{sec:valid-sudoku}\n\\myenddot\n\n\n\\section{Word Search} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:word-search}\n\n\n\\subsubsection{描述}\nGiven a 2D board and a word, find if the word exists in the grid.\n\nThe word can be constructed from letters of sequentially adjacent cell, where \\fn{\"adjacent\"} cells are those horizontally or vertically neighbouring. The same letter cell may not be used more than once.\n\nFor example,\nGiven board =\n\\begin{Code}\n[\n  [\"ABCE\"],\n  [\"SFCS\"],\n  [\"ADEE\"]\n]\n\\end{Code}\nword = \\fn{\"ABCCED\"}, -> returns \\fn{true},\\\\\nword = \\fn{\"SEE\"}, -> returns \\fn{true},\\\\\nword = \\fn{\"ABCB\"}, -> returns \\fn{false}.\n\n\n\\subsubsection{分析}\n无。\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Word Search\n// 深搜，递归\n// 时间复杂度O(n^2*m^2)，空间复杂度O(n^2)\nclass Solution {\npublic:\n    bool exist(const vector<vector<char> > &board, const string& word) {\n        const int m = board.size();\n        const int n = board[0].size();\n        vector<vector<bool> > visited(m, vector<bool>(n, false));\n        for (int i = 0; i < m; ++i)\n            for (int j = 0; j < n; ++j)\n                if (dfs(board, word, 0, i, j, visited))\n                    return true;\n        return false;\n    }\nprivate:\n    static bool dfs(const vector<vector<char> > &board, const string &word,\n            int index, int x, int y, vector<vector<bool> > &visited) {\n        if (index == word.size())\n            return true; // 收敛条件\n\n        if (x < 0 || y < 0 || x >= board.size() || y >= board[0].size())\n            return false;  // 越界，终止条件\n\n        if (visited[x][y]) return false; // 已经访问过，剪枝\n\n        if (board[x][y] != word[index]) return false; // 不相等，剪枝\n\n        visited[x][y] = true;\n        bool ret = dfs(board, word, index + 1, x - 1, y, visited) || // 上\n                dfs(board, word, index + 1, x + 1, y, visited)    || // 下\n                dfs(board, word, index + 1, x, y - 1, visited)    || // 左\n                dfs(board, word, index + 1, x, y + 1, visited);      // 右\n        visited[x][y] = false;\n        return ret;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item 无\n\\myenddot\n\n\n\\section{小结} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:dfs-template}\n\n\n\\subsection{适用场景}\n\n\\textbf{输入数据}：如果是递归数据结构，如单链表，二叉树，集合，则百分之百可以用深搜；如果是非递归数据结构，如一维数组，二维数组，字符串，图，则概率小一些。\n\n\\textbf{状态转换图}：树或者图。\n\n\\textbf{求解目标}：必须要走到最深（例如对于树，必须要走到叶子节点）才能得到一个解，这种情况适合用深搜。\n\n\n\\subsection{思考的步骤}\n\\begin{enumerate}\n\\item 是求路径条数，还是路径本身（或动作序列）？深搜最常见的三个问题，求可行解的总数，求一个可行解，求所有可行解。\n    \\begin{enumerate}\n\t\\item 如果是路径条数，则不需要存储路径。\n    \\item 如果是求路径本身，则要用一个数组\\fn{path[]}存储路径。跟宽搜不同，宽搜虽然最终求的也是一条路径，但是需要存储扩展过程中的所有路径，在没找到答案之前所有路径都不能放弃；而深搜，在搜索过程中始终只有一条路径，因此用一个数组就足够了。\n    \\end{enumerate}\n\n\\item 只要求一个解，还是要求所有解？如果只要求一个解，那找到一个就可以返回；如果要求所有解，找到了一个后，还要继续扩展，直到遍历完。广搜一般只要求一个解，因而不需要考虑这个问题（广搜当然也可以求所有解，这时需要扩展到所有叶子节点，相当于在内存中存储整个状态转换图，非常占内存，因此广搜不适合解这类问题）。\n\n\\item 如何表示状态？即一个状态需要存储哪些些必要的数据，才能够完整提供如何扩展到下一步状态的所有信息。跟广搜不同，深搜的惯用写法，不是把数据记录在状态\\fn{struct}里，而是添加函数参数（有时为了节省递归堆栈，用全局变量），\\fn{struct}里的字段与函数参数一一对应。\n\n\\item 如何扩展状态？这一步跟上一步相关。状态里记录的数据不同，扩展方法就不同。对于固定不变的数据结构（一般题目直接给出，作为输入数据），如二叉树，图等，扩展方法很简单，直接往下一层走，对于隐式图，要先在第1步里想清楚状态所带的数据，想清楚了这点，那如何扩展就很简单了。\n\n\\item 终止条件是什么？终止条件是指到了不能扩展的末端节点。对于树，是叶子节点，对于图或隐式图，是出度为0的节点。\n\n\\item {收敛条件是什么？收敛条件是指找到了一个合法解的时刻。如果是正向深搜（父状态处理完了才进行递归，即父状态不依赖子状态，递归语句一定是在最后，尾递归），则是指是否达到目标状态；如果是逆向深搜（处理父状态时需要先知道子状态的结果，此时递归语句不在最后），则是指是否到达初始状态。\n\n由于很多时候终止条件和收敛条件是是合二为一的，因此很多人不区分这两种条件。仔细区分这两种条件，还是很有必要的。\n\n为了判断是否到了收敛条件，要在函数接口里用一个参数记录当前的位置（或距离目标还有多远）。如果是求一个解，直接返回这个解；如果是求所有解，要在这里收集解，即把第一步中表示路径的数组\\fn{path[]}复制到解集合里。}\n\n\\item 关于判重\n    \\begin{enumerate}\n    \\item 是否需要判重？如果状态转换图是一棵树，则不需要判重，因为在遍历过程中不可能重复；如果状态转换图是一个DAG，则需要判重。这一点跟BFS不一样，BFS的状态转换图总是DAG，必须要判重。\n    \\item 怎样判重？跟广搜相同，见第 \\S \\ref{sec:bfs-template} 节。同时，DAG说明存在重叠子问题，此时可以用缓存加速，见第8步。\n    \\end{enumerate}\n\n\\item 如何加速？\n    \\begin{enumerate}\n    \\item 剪枝。深搜一定要好好考虑怎么剪枝，成本小收益大，加几行代码，就能大大加速。这里没有通用方法，只能具体问题具体分析，要充分观察，充分利用各种信息来剪枝，在中间节点提前返回。\n    \\item 缓存。\n        \\begin{enumerate}\n            \\item 前提条件：状态转换图是一个DAG。DAG=>存在重叠子问题=>子问题的解会被重复利用，用缓存自然会有加速效果。如果依赖关系是树状的（例如树，单链表等），没必要加缓存，因为子问题只会一层层往下，用一次就再也不会用到，加了缓存也没什么加速效果。\n            \\item 具体实现：可以用数组或HashMap。维度简单的，用数组；维度复杂的，用HashMap，C++有\\fn{map}，C++ 11以后有\\fn{unordered_map}，比\\fn{map}快。\n        \\end{enumerate}\n    \n    \\end{enumerate}\n\\end{enumerate}\n\n拿到一个题目，当感觉它适合用深搜解决时，在心里面把上面8个问题默默回答一遍，代码基本上就能写出来了。对于树，不需要回答第5和第8个问题。如果读者对上面的经验总结看不懂或感觉“不实用”，很正常，因为这些经验总结是我做了很多题目后总结出来的，从思维的发展过程看，“经验总结”要晚于感性认识，所以这时候建议读者先做做前面的题目，积累一定的感性认识后，再回过头来看这一节的总结，一定会有共鸣。\n\n\n\\subsection{代码模板}\n\n\\begin{Codex}[label=dfs_template.cpp]\n/**\n * dfs模板.\n * @param[in] input 输入数据指针\n * @param[out] path 当前路径，也是中间结果\n * @param[out] result 存放最终结果\n * @param[inout] cur or gap 标记当前位置或距离目标的距离\n * @return 路径长度，如果是求路径本身，则不需要返回长度\n */\nvoid dfs(type &input, type &path, type &result, int cur or gap) {\n    if (数据非法) return 0;   // 终止条件\n    if (cur == input.size()) { // 收敛条件\n    // if (gap == 0) {\n        将path放入result\n    }\n\n    if (可以剪枝) return;\n\n    for(...) { // 执行所有可能的扩展动作\n        执行动作，修改path\n        dfs(input, step + 1 or gap--, result);\n        恢复path\n    }\n}\n\\end{Codex}\n\n\n\\subsection{深搜与回溯法的区别}\n深搜(Depth-first search, DFS)的定义见\\myurl{http://en.wikipedia.org/wiki/Depth_first_search}，回溯法(backtracking)的定义见\\myurl{http://en.wikipedia.org/wiki/Backtracking}\n\n\\textbf{回溯法 = 深搜 + 剪枝}。一般大家用深搜时，或多或少会剪枝，因此深搜与回溯法没有什么不同，可以在它们之间画上一个等号。本书同时使用深搜和回溯法两个术语，但读者可以认为二者等价。\n\n深搜一般用递归(recursion)来实现，这样比较简洁。\n\n深搜能够在候选答案生成到一半时，就进行判断，抛弃不满足要求的答案，所以深搜比暴力搜索法要快。\n\n\n\\subsection{深搜与递归的区别}\n\\label{sec:dfs-vs-recursion}\n\n深搜经常用递归(recursion)来实现，二者常常同时出现，导致很多人误以为他俩是一个东西。\n\n深搜，是逻辑意义上的算法，递归，是一种物理意义上的实现，它和迭代(iteration)是对应的。深搜，可以用递归来实现，也可以用栈来实现；而递归，一般总是用来实现深搜。可以说，\\textbf{递归一定是深搜，深搜不一定用递归}。\n\n递归有两种加速策略，一种是\\textbf{剪枝(prunning)}，对中间结果进行判断，提前返回；一种是\\textbf{缓存}，缓存中间结果，防止重复计算，用空间换时间。\n\n其实，递归+缓存，就是 memoization。所谓\\textbf{memoization}（翻译为备忘录法，见第 \\S \\ref{sec:dp-vs-memoization}节），就是\"top-down with cache\"（自顶向下+缓存），它是Donald Michie 在1968年创造的术语，表示一种优化技术，在top-down 形式的程序中，使用缓存来避免重复计算，从而达到加速的目的。\n\n\\textbf{memoization 不一定用递归}，就像深搜不一定用递归一样，可以在迭代(iterative)中使用 memoization 。\\textbf{递归也不一定用 memoization}，可以用memoization来加速，但不是必须的。只有当递归使用了缓存，它才是 memoization 。\n\n既然递归一定是深搜，为什么很多书籍都同时使用这两个术语呢？在递归味道更浓的地方，一般用递归这个术语，在深搜更浓的场景下，用深搜这个术语，读者心里要弄清楚他俩大部分时候是一回事。在单链表、二叉树等递归数据结构上，递归的味道更浓，这时用递归这个术语；在图、隐式图等数据结构上，深搜的味道更浓，这时用深搜这个术语。\n"
  },
  {
    "path": "C++/chapDivideAndConquer.tex",
    "content": "\\chapter{分治法}\n\n\n\\section{Pow(x,n)} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:pow}\n\n\n\\subsubsection{描述}\nImplement pow(x, n).\n\n\n\\subsubsection{分析}\n二分法，$x^n = x^{n/2} \\times x^{n/2} \\times x^{n\\%2}$\n\n\n\\subsubsection{代码}\n\\begin{Code}\n//LeetCode, Pow(x, n)\n// 二分法，$x^n = x^{n/2} * x^{n/2} * x^{n\\%2}$\n// 时间复杂度O(logn)，空间复杂度O(1)\nclass Solution {\npublic:\n    double myPow(double x, int n) {\n        if (n < 0) return 1.0 / power(x, -n);\n        else return power(x, n);\n    }\nprivate:\n    double power(double x, int n) {\n        if (n == 0) return 1;\n        double v = power(x, n / 2);\n        if (n % 2 == 0) return v * v;\n        else return v * v * x;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\n\\begindot\n\\item Sqrt(x)，见 \\S \\ref{sec:sqrt}\n\\myenddot\n\n\n\\section{Sqrt(x)} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:sqrt}\n\n\\subsubsection{描述}\nImplement int \\fn{sqrt(int x)}.\n\nCompute and return the square root of \\fn{x}.\n\n\n\\subsubsection{分析}\n二分查找\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Sqrt(x)\n// 二分查找\n// 时间复杂度O(logn)，空间复杂度O(1)\nclass Solution {\npublic:\n    int mySqrt(int x) {\n        int left = 1, right = x / 2;\n        int last_mid;  // 记录最近一次mid\n\n        if (x < 2) return x;\n\n        while(left <= right) {\n            const int mid = left + (right - left) / 2;\n            if(x / mid > mid) { // 不要用 x > mid * mid，会溢出\n                left = mid + 1;\n                last_mid = mid;\n            } else if(x / mid < mid) {\n                right = mid - 1;\n            } else {\n                return mid;\n            }\n        }\n        return last_mid;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Pow(x)，见 \\S \\ref{sec:pow}\n\\myenddot\n"
  },
  {
    "path": "C++/chapDynamicProgramming.tex",
    "content": "\\chapter{动态规划}\n\n\n\\section{Triangle} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:triangle}\n\n\n\\subsubsection{描述}\nGiven a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.\n\nFor example, given the following triangle\n\\begin{Code}\n[\n     [2],\n    [3,4],\n   [6,5,7],\n  [4,1,8,3]\n]\n\\end{Code}\nThe minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).\n\nNote: Bonus point if you are able to do this using only $O(n)$ extra space, where n is the total number of rows in the triangle.\n\n\n\\subsubsection{分析}\n设状态为$f(i, j)$，表示从从位置$(i,j)$出发，路径的最小和，则状态转移方程为\n$$\nf(i,j)=\\min\\left\\{f(i+1,j),f(i+1,j+1)\\right\\}+(i,j)\n$$\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Triangle\n// 时间复杂度O(n^2)，空间复杂度O(1)\nclass Solution {\npublic:\n    int minimumTotal (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] += min(triangle[i + 1][j],\n                        triangle[i + 1][j + 1]);\n\n        return triangle [0][0];\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item 无\n\\myenddot\n\n\n\\section{Maximum Subarray} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:maximum-subarray}\n\n\n\\subsubsection{描述}\nFind the contiguous subarray within an array (containing at least one number) which has the largest sum.\n\nFor example, given the array \\code{[−2,1,−3,4,−1,2,1,−5,4]},\nthe contiguous subarray \\code{[4,−1,2,1]} has the largest \\code{sum = 6}.\n\n\n\\subsubsection{分析}\n最大连续子序列和，非常经典的题。\n\n当我们从头到尾遍历这个数组的时候，对于数组里的一个整数，它有几种选择呢？它只有两种选择： 1、加入之前的SubArray；2. 自己另起一个SubArray。那什么时候会出现这两种情况呢？\n\n如果之前SubArray的总体和大于0的话，我们认为其对后续结果是有贡献的。这种情况下我们选择加入之前的SubArray\n\n如果之前SubArray的总体和为0或者小于0的话，我们认为其对后续结果是没有贡献，甚至是有害的（小于0时）。这种情况下我们选择以这个数字开始，另起一个SubArray。\n\n设状态为\\fn{f[j]}，表示以\\fn{S[j]}结尾的最大连续子序列和，则状态转移方程如下：\n\\begin{eqnarray}\nf[j] &=& \\max\\left\\{f[j-1]+S[j],S[j]\\right\\}, \\text{ 其中 }1 \\leq j \\leq n \\nonumber \\\\\ntarget &=& \\max\\left\\{f[j]\\right\\}, \\text{ 其中 }1 \\leq j \\leq n \\nonumber\n\\end{eqnarray}\n\n解释如下：\n\\begindot\n\\item 情况一，S[j]不独立，与前面的某些数组成一个连续子序列，则最大连续子序列和为$f[j-1]+S[j]$。\n\\item 情况二，S[j]独立划分成为一段，即连续子序列仅包含一个数S[j]，则最大连续子序列和为$S[j]$。\n\\myenddot  \n\n其他思路：\n\\begindot\n\\item 思路2：直接在i到j之间暴力枚举，复杂度是$O(n^3)$\n\\item 思路3：处理后枚举，连续子序列的和等于两个前缀和之差，复杂度$O(n^2)$。\n\\item 思路4：分治法，把序列分为两段，分别求最大连续子序列和，然后归并，复杂度$O(n\\log n)$\n\\item 思路5：把思路2$O(n^2)$的代码稍作处理，得到$O(n)$的算法\n\\item 思路6：当成M=1的最大M子段和\n\\myenddot\n\n\n\\subsubsection{动规}\n\\begin{Code}\n// LeetCode, Maximum Subarray\n// 时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    int maxSubArray(vector<int>& nums) {\n        int result = INT_MIN, f = 0;\n        for (int i = 0; i < nums.size(); ++i) {\n            f = max(f + nums[i], nums[i]);\n            result = max(result, f);\n        }\n        return result;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{思路5}\n\\begin{Code}\n// LeetCode, Maximum Subarray\n// 时间复杂度O(n)，空间复杂度O(n)\nclass Solution {\npublic:\n    int maxSubArray(vector<int>& A) {\n        return mcss(A.begin(), A.end());\n    }\nprivate:\n    // 思路5，求最大连续子序列和\n    template <typename Iter>\n    static int mcss(Iter begin, Iter end) {\n        int result, cur_min;\n        const int n = distance(begin, end);\n        int *sum = new int[n + 1];  // 前n项和\n\n        sum[0] = 0;\n        result = INT_MIN;\n        cur_min = sum[0];\n        for (int i = 1; i <= n; i++) {\n            sum[i] = sum[i - 1] + *(begin  + i - 1);\n        }\n        for (int i = 1; i <= n; i++) {\n            result = max(result, sum[i] - cur_min);\n            cur_min = min(cur_min, sum[i]);\n        }\n        delete[] sum;\n        return result;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Binary Tree Maximum Path Sum，见 \\S \\ref{sec:binary-tree-maximum-path-sum}\n\\myenddot\n\n\n\\section{Palindrome Partitioning II} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:palindrome-partitioning-ii}\n\n\n\\subsubsection{描述}\nGiven a string s, partition s such that every substring of the partition is a palindrome.\n\nReturn the minimum cuts needed for a palindrome partitioning of s.\n\nFor example, given \\code{s = \"aab\"},\n\nReturn 1 since the palindrome partitioning \\code{[\"aa\",\"b\"]} could be produced using 1 cut.\n\n\n\\subsubsection{分析}\n定义状态\\fn{f(i,j)}表示区间\\fn{[i,j]}之间最小的cut数，则状态转移方程为 \n$$\nf(i,j)=\\min\\left\\{f(i,k)+f(k+1,j)\\right\\}, i \\leq k \\leq j, 0 \\leq i \\leq j<n\n$$\n这是一个二维函数，实际写代码比较麻烦。\n \n所以要转换成一维DP。如果每次，从i往右扫描，每找到一个回文就算一次DP的话，就可以转换为\\code{f(i)=区间[i, n-1]之间最小的cut数}，n为字符串长度，则状态转移方程为\n$$\nf(i)=\\min\\left\\{f(j+1)+1\\right\\}, i \\leq j<n\n$$\n\n一个问题出现了，就是如何判断\\fn{[i,j]}是否是回文？每次都从i到j比较一遍？太浪费了，这里也是一个DP问题。\n\n定义状态\\fn{P[i][j] = true if [i,j]为回文}，那么\n\\begin{Code}\nP[i][j] = str[i] == str[j] && P[i+1][j-1]\n\\end{Code}\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Palindrome Partitioning II\n// 时间复杂度O(n^2)，空间复杂度O(n^2)\nclass Solution {\npublic:\n    int minCut(const string& s) {\n        const int n = s.size();\n        int f[n+1];\n        bool p[n][n];\n        fill_n(&p[0][0], n * n, false);\n        //the worst case is cutting by each char\n        for (int i = 0; i <= n; i++)\n            f[i] = n - 1 - i; // 最后一个f[n]=-1\n        for (int i = n - 1; i >= 0; i--) {\n            for (int j = i; j < n; j++) {\n                if (s[i] == s[j] && (j - i < 2 || p[i + 1][j - 1])) {\n                    p[i][j] = true;\n                    f[i] = min(f[i], f[j + 1] + 1);\n                }\n            }\n        }\n        return f[0];\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Palindrome Partitioning，见 \\S \\ref{sec:palindrome-partitioning}\n\\myenddot\n\n\n\\section{Maximal Rectangle} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:maximal-rectangle}\n\n\n\\subsubsection{描述}\nGiven a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.\n\n\n\\subsubsection{分析}\n无\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Maximal Rectangle\n// 时间复杂度O(n^2)，空间复杂度O(n)\nclass Solution {\npublic:\n    int maximalRectangle(vector<vector<char> > &matrix) {\n        if (matrix.empty())  return 0;\n\n        const int m = matrix.size();\n        const int n = matrix[0].size();\n        vector<int> H(n, 0);\n        vector<int> L(n, 0);\n        vector<int> R(n, n);\n\n        int ret = 0;\n        for (int i = 0; i < m; ++i) {\n            int left = 0, right = n;\n            // calculate L(i, j) from left to right\n            for (int j = 0; j < n; ++j) {\n                if (matrix[i][j] == '1') {\n                    ++H[j];\n                    L[j] = max(L[j], left);\n                } else {\n                    left = j+1;\n                    H[j] = 0; L[j] = 0; R[j] = n;\n                }\n            }\n            // calculate R(i, j) from right to left\n            for (int j = n-1; j >= 0; --j) {\n                if (matrix[i][j] == '1') {\n                    R[j] = min(R[j], right);\n                    ret = max(ret, H[j]*(R[j]-L[j]));\n                } else {\n                    right = j;\n                }\n            }\n        }\n        return ret;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\n\\begindot\n\\item 无\n\\myenddot\n\n\n\\section{Best Time to Buy and Sell Stock III} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:best-time-to-buy-and-sell-stock-iii}\n\n\n\\subsubsection{描述}\nSay you have an array for which the i-th element is the price of a given stock on day i.\n\nDesign an algorithm to find the maximum profit. You may complete at most two transactions.\n\nNote: You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).\n\n\n\\subsubsection{分析}\n设状态$f(i)$，表示区间$[0,i](0 \\leq i \\leq n-1)$的最大利润，状态$g(i)$，表示区间$[i, n-1](0 \\leq i \\leq n-1)$的最大利润，则最终答案为$\\max\\left\\{f(i)+g(i)\\right\\},0 \\leq i \\leq n-1$。\n\n允许在一天内买进又卖出，相当于不交易，因为题目的规定是最多两次，而不是一定要两次。\n\n将原数组变成差分数组，本题也可以看做是最大$m$子段和，$m=2$，参考代码：\\myurl{https://gist.github.com/soulmachine/5906637}\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Best Time to Buy and Sell Stock III\n// 时间复杂度O(n)，空间复杂度O(n)\nclass Solution {\npublic:\n    int maxProfit(vector<int>& prices) {\n        if (prices.size() < 2) return 0;\n\n        const int n = prices.size();\n        vector<int> f(n, 0);\n        vector<int> g(n, 0);\n\n        for (int i = 1, valley = prices[0]; i < n; ++i) {\n            valley = min(valley, prices[i]);\n            f[i] = max(f[i - 1], prices[i] - valley);\n        }\n\n        for (int i = n - 2, peak = prices[n - 1]; i >= 0; --i) {\n            peak = max(peak, prices[i]);\n            g[i] = max(g[i], peak - prices[i]);\n        }\n\n        int max_profit = 0;\n        for (int i = 0; i < n; ++i)\n            max_profit = max(max_profit, f[i] + g[i]);\n\n        return max_profit;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Best Time to Buy and Sell Stock，见 \\S \\ref{sec:best-time-to-buy-and-sell-stock}\n\\item Best Time to Buy and Sell Stock II，见 \\S \\ref{sec:best-time-to-buy-and-sell-stock-ii}\n\\myenddot\n\n\n\\section{Interleaving String} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:interleaving-string}\n\n\n\\subsubsection{描述}\nGiven $s1, s2, s3$, find whether $s3$ is formed by the interleaving of $s1$ and $s2$.\n\nFor example, Given: \\code{s1 = \"aabcc\", s2 = \"dbbca\"},\n\nWhen \\code{s3 = \"aadbbcbcac\"}, return true.\n\nWhen \\code{s3 = \"aadbbbaccc\"}, return false.\n\n\n\\subsubsection{分析}\n设状态\\fn{f[i][j]}，表示\\fn{s1[0,i]}和\\fn{s2[0,j]}，匹配\\fn{s3[0, i+j]}。如果s1的最后一个字符等于s3的最后一个字符，则\\fn{f[i][j]=f[i-1][j]}；如果s2的最后一个字符等于s3的最后一个字符，则\\fn{f[i][j]=f[i][j-1]}。因此状态转移方程如下：\n\\begin{Code}\nf[i][j] = (s1[i - 1] == s3 [i + j - 1] && f[i - 1][j])\n       || (s2[j - 1] == s3 [i + j - 1] && f[i][j - 1]);\n\\end{Code}\n\n\n\\subsubsection{递归}\n\\begin{Code}\n// LeetCode, Interleaving String\n// 递归，会超时，仅用来帮助理解\nclass Solution {\npublic:\n    bool isInterleave(const string& s1, const string& s2, const string& s3) {\n        if (s3.length() != s1.length() + s2.length())\n            return false;\n\n        return isInterleave(begin(s1), end(s1), begin(s2), end(s2),\n                begin(s3), end(s3));\n    }\n\n    template<typename InIt>\n    bool isInterleave(InIt first1, InIt last1, InIt first2, InIt last2,\n            InIt first3, InIt last3) {\n        if (first3 == last3)\n            return first1 == last1 && first2 == last2;\n\n        return (*first1 == *first3\n                && isInterleave(next(first1), last1, first2, last2,\n                        next(first3), last3))\n                || (*first2 == *first3\n                        && isInterleave(first1, last1, next(first2), last2,\n                                next(first3), last3));\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{动规}\n\\begin{Code}\n// LeetCode, Interleaving String\n// 二维动规，时间复杂度O(n^2)，空间复杂度O(n^2)\nclass Solution {\npublic:\n    bool isInterleave(const string& s1, const string& s2, const string& s3) {\n        if (s3.length() != s1.length() + s2.length())\n            return false;\n\n        vector<vector<bool>> f(s1.length() + 1,\n                vector<bool>(s2.length() + 1, true));\n\n        for (size_t i = 1; i <= s1.length(); ++i)\n            f[i][0] = f[i - 1][0] && s1[i - 1] == s3[i - 1];\n\n        for (size_t i = 1; i <= s2.length(); ++i)\n            f[0][i] = f[0][i - 1] && s2[i - 1] == s3[i - 1];\n\n        for (size_t i = 1; i <= s1.length(); ++i)\n            for (size_t j = 1; j <= s2.length(); ++j)\n                f[i][j] = (s1[i - 1] == s3[i + j - 1] && f[i - 1][j])\n                        || (s2[j - 1] == s3[i + j - 1] && f[i][j - 1]);\n\n        return f[s1.length()][s2.length()];\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{动规+滚动数组}\n\\begin{Code}\n// LeetCode, Interleaving String\n// 二维动规+滚动数组，时间复杂度O(n^2)，空间复杂度O(n)\nclass Solution {\npublic:\n    bool isInterleave(const string& s1, const string& s2, const string& s3) {\n        if (s1.length() + s2.length() != s3.length())\n            return false;\n\n        if (s1.length() < s2.length())\n            return isInterleave(s2, s1, s3);\n\n        vector<bool> f(s2.length() + 1, true);\n\n        for (size_t i = 1; i <= s2.length(); ++i)\n            f[i] = s2[i - 1] == s3[i - 1] && f[i - 1];\n\n        for (size_t i = 1; i <= s1.length(); ++i) {\n            f[0] = s1[i - 1] == s3[i - 1] && f[0];\n\n            for (size_t j = 1; j <= s2.length(); ++j)\n                f[j] = (s1[i - 1] == s3[i + j - 1] && f[j])\n                        || (s2[j - 1] == s3[i + j - 1] && f[j - 1]);\n        }\n\n        return f[s2.length()];\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item 无\n\\myenddot\n\n\n\\section{Scramble String} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:scramble-string}\n\n\n\\subsubsection{描述}\nGiven a string $s1$, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively.\n\nBelow is one possible representation of \\code{s1 = \"great\"}:\n\\begin{Code}\n    great\n   /    \\\n  gr    eat\n / \\    /  \\\ng   r  e   at\n           / \\\n          a   t\n\\end{Code}\n\nTo scramble the string, we may choose any non-leaf node and swap its two children.\n\nFor example, if we choose the node \\code{\"gr\"} and swap its two children, it produces a scrambled string \\code{\"rgeat\"}.\n\\begin{Code}\n    rgeat\n   /    \\\n  rg    eat\n / \\    /  \\\nr   g  e   at\n           / \\\n          a   t\n\\end{Code}\n\nWe say that \\code{\"rgeat\"} is a scrambled string of \\code{\"great\"}.\n\nSimilarly, if we continue to swap the children of nodes \\code{\"eat\"} and \\code{\"at\"}, it produces a scrambled string \\code{\"rgtae\"}.\n\\begin{Code}\n    rgtae\n   /    \\\n  rg    tae\n / \\    /  \\\nr   g  ta  e\n       / \\\n      t   a\n\\end{Code}\n\nWe say that \\code{\"rgtae\"} is a scrambled string of \\code{\"great\"}.\n\nGiven two strings $s1$ and $s2$ of the same length, determine if $s2$ is a scrambled string of $s1$.\n\n\n\\subsubsection{分析}\n首先想到的是递归（即深搜），对两个string进行分割，然后比较四对字符串。代码虽然简单，但是复杂度比较高。有两种加速策略，一种是剪枝，提前返回；一种是加缓存，缓存中间结果，即memoization（翻译为记忆化搜索）。\n\n剪枝可以五花八门，要充分观察，充分利用信息，找到能让节点提前返回的条件。例如，判断两个字符串是否互为scamble，至少要求每个字符在两个字符串中出现的次数要相等，如果不相等则返回false。\n\n加缓存，可以用数组或HashMap。本题维数较高，用HashMap，\\fn{map}和\\fn{unordered_map}均可。\n\n既然可以用记忆化搜索，这题也一定可以用动规。设状态为\\fn{f[n][i][j]}，表示长度为$n$，起点为\\fn{s1[i]}和起点为\\fn{s2[j]}两个字符串是否互为scramble，则状态转移方程为\n\\begin{Code}\nf[n][i][j]} =  (f[k][i][j] && f[n-k][i+k][j+k]) \n            || (f[k][i][j+n-k] && f[n-k][i+k][j])\n\\end{Code}\n\n\n\\subsubsection{递归}\n\n\\begin{Code}\n// LeetCode, Scramble String\n// 递归，会超时，仅用来帮助理解\n// 时间复杂度O(n^6)，空间复杂度O(1)\nclass Solution {\npublic:\n    bool isScramble(const string& s1, const string& s2) {\n        return isScramble(s1.begin(), s1.end(), s2.begin());\n    }\nprivate:\n    typedef string::iterator Iterator;\n    bool isScramble(Iterator first1, Iterator last1, Iterator first2) {\n        auto length = distance(first1, last1);\n        auto last2 = next(first2, length);\n\n        if (length == 1) return *first1 == *first2;\n\n        for (int i = 1; i < length; ++i)\n            if ((isScramble(first1, first1 + i, first2)\n                 && isScramble(first1 + i, last1, first2 + i))\n                    || (isScramble(first1, first1 + i, last2 - i)\n                            && isScramble(first1 + i, last1, first2)))\n                return true;\n\n        return false;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{动规}\n\\begin{Code}\n// LeetCode, Scramble String\n// 动规，时间复杂度O(n^3)，空间复杂度O(n^3)\nclass Solution {\npublic:\n    bool isScramble(const string& s1, const string& s2) {\n        const int N = s1.size();\n        if (N != s2.size()) return false;\n\n        // f[n][i][j]，表示长度为n，起点为s1[i]和\n        // 起点为s2[j]两个字符串是否互为scramble\n        bool f[N + 1][N][N];\n        fill_n(&f[0][0][0], (N + 1) * N * N, false);\n\n        for (int i = 0; i < N; i++)\n            for (int j = 0; j < N; j++)\n                f[1][i][j] = s1[i] == s2[j];\n\n        for (int n = 1; n <= N; ++n) {\n            for (int i = 0; i + n <= N; ++i) {\n                for (int j = 0; j + n <= N; ++j) {\n                    for (int k = 1; k < n; ++k) {\n                        if ((f[k][i][j] && f[n - k][i + k][j + k]) ||\n                                (f[k][i][j + n - k] && f[n - k][i + k][j])) {\n                            f[n][i][j] = true;\n                            break;\n                        }\n                    }\n                }\n            }\n        }\n        return f[N][0][0];\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{递归+剪枝}\n\\begin{Code}\n// LeetCode, Scramble String\n// 递归+剪枝\n// 时间复杂度O(n^6)，空间复杂度O(1)\nclass Solution {\npublic:\n    bool isScramble(const string& s1, const string& s2) {\n        return isScramble(s1.begin(), s1.end(), s2.begin());\n    }\nprivate:\n    typedef string::const_iterator Iterator;\n    bool isScramble(Iterator first1, Iterator last1, Iterator first2) {\n        auto length = distance(first1, last1);\n        auto last2 = next(first2, length);\n        if (length == 1) return *first1 == *first2;\n\n        // 剪枝，提前返回\n        int A[26]; // 每个字符的计数器\n        fill(A, A + 26, 0);\n        for(int i = 0; i < length; i++) A[*(first1+i)-'a']++;\n        for(int i = 0; i < length; i++) A[*(first2+i)-'a']--;\n        for(int i = 0; i < 26; i++) if (A[i] != 0) return false;\n\n        for (int i = 1; i < length; ++i)\n            if ((isScramble(first1, first1 + i, first2)\n                 && isScramble(first1 + i, last1, first2 + i))\n                    || (isScramble(first1, first1 + i, last2 - i)\n                            && isScramble(first1 + i, last1, first2)))\n                return true;\n\n        return false;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{备忘录法}\n\\begin{Code}\n// LeetCode, Scramble String\n// 递归+map做cache\n// 时间复杂度O(n^3)，空间复杂度O(n^3), TLE\nclass Solution {\npublic:\n    bool isScramble(const string& s1, const string& s2) {\n        cache.clear();\n        return isScramble(s1.begin(), s1.end(), s2.begin());\n    }\nprivate:\n    typedef string::const_iterator Iterator;\n    map<tuple<Iterator, Iterator, Iterator>, bool> cache;\n\n    bool isScramble(Iterator first1, Iterator last1, Iterator first2) {\n        auto length = distance(first1, last1);\n        auto last2 = next(first2, length);\n\n        if (length == 1) return *first1 == *first2;\n\n        for (int i = 1; i < length; ++i)\n            if ((getOrUpdate(first1, first1 + i, first2)\n                    && getOrUpdate(first1 + i, last1, first2 + i))\n                    || (getOrUpdate(first1, first1 + i, last2 - i)\n                            && getOrUpdate(first1 + i, last1, first2)))\n                return true;\n\n        return false;\n    }\n\n    bool getOrUpdate(Iterator first1, Iterator last1, Iterator first2) {\n        auto key = make_tuple(first1, last1, first2);\n        auto pos = cache.find(key);\n\n        return (pos != cache.end()) ?\n                pos->second : (cache[key] = isScramble(first1, last1, first2));\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{备忘录法}\n\\begin{Code}\ntypedef string::const_iterator Iterator;\ntypedef tuple<Iterator, Iterator, Iterator> Key;\n// 定制一个哈希函数\nnamespace std {\ntemplate<> struct hash<Key> {\n    size_t operator()(const Key & x) const {\n        Iterator first1, last1, first2;\n        tie(first1, last1, first2) = x;\n\n        int result = *first1;\n        result = result * 31 + *last1;\n        result = result * 31 + *first2;\n        result = result * 31 + *(next(first2, distance(first1, last1)-1));\n        return result;\n    }\n};\n}\n\n// LeetCode, Scramble String\n// 递归+unordered_map做cache，比map快\n// 时间复杂度O(n^3)，空间复杂度O(n^3)\nclass Solution {\npublic:\n    unordered_map<Key, bool> cache;\n\n    bool isScramble(const string& s1, const string& s2) {\n        cache.clear();\n        return isScramble(s1.begin(), s1.end(), s2.begin());\n    }\n\n    bool isScramble(Iterator first1, Iterator last1, Iterator first2) {\n        auto length = distance(first1, last1);\n        auto last2 = next(first2, length);\n\n        if (length == 1)\n            return *first1 == *first2;\n\n        for (int i = 1; i < length; ++i)\n            if ((getOrUpdate(first1, first1 + i, first2)\n                    && getOrUpdate(first1 + i, last1, first2 + i))\n                    || (getOrUpdate(first1, first1 + i, last2 - i)\n                            && getOrUpdate(first1 + i, last1, first2)))\n                return true;\n\n        return false;\n    }\n\n    bool getOrUpdate(Iterator first1, Iterator last1, Iterator first2) {\n        auto key = make_tuple(first1, last1, first2);\n        auto pos = cache.find(key);\n\n        return (pos != cache.end()) ?\n                pos->second : (cache[key] = isScramble(first1, last1, first2));\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item 无\n\\myenddot\n\n\n\\section{Minimum Path Sum} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:minimum-path-sum}\n\n\n\\subsubsection{描述}\nGiven a $m \\times n$ grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.\n\nNote: You can only move either down or right at any point in time\n\n\n\\subsubsection{分析}\n跟 Unique Paths (见 \\S \\ref{sec:unique-paths}) 很类似。\n\n设状态为\\fn{f[i][j]}，表示从起点$(0,0)$到达$(i,j)$的最小路径和，则状态转移方程为：\n\\begin{Code}\nf[i][j]=min(f[i-1][j], f[i][j-1])+grid[i][j]\n\\end{Code}\n\n\n\\subsubsection{备忘录法}\n\\begin{Code}\n// LeetCode, Minimum Path Sum\n// 备忘录法\nclass Solution {\npublic:\n    int minPathSum(vector<vector<int> > &grid) {\n        const int m = grid.size();\n        const int n = grid[0].size();\n        this->f = vector<vector<int> >(m, vector<int>(n, -1));\n        return dfs(grid, m-1, n-1);\n    }\nprivate:\n    vector<vector<int> > f;  // 缓存\n\n    int dfs(const vector<vector<int> > &grid, int x, int y) {\n        if (x < 0 || y < 0) return INT_MAX; // 越界，终止条件，注意，不是0\n\n        if (x == 0 && y == 0) return grid[0][0]; // 回到起点，收敛条件\n\n        return min(getOrUpdate(grid, x - 1, y),\n                getOrUpdate(grid, x, y - 1)) + grid[x][y];\n    }\n\n    int getOrUpdate(const vector<vector<int> > &grid, int x, int y) {\n        if (x < 0 || y < 0) return INT_MAX; // 越界，注意，不是0\n        if (f[x][y] >= 0) return f[x][y];\n        else return f[x][y] = dfs(grid, x, y);\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{动规}\n\\begin{Code}\n// LeetCode, Minimum Path Sum\n// 二维动规\nclass Solution {\npublic:\n    int minPathSum(vector<vector<int> > &grid) {\n        if (grid.size() == 0) return 0;\n        const int m = grid.size();\n        const int n = grid[0].size();\n\n        int f[m][n];\n        f[0][0] = grid[0][0];\n        for (int i = 1; i < m; i++) {\n            f[i][0] = f[i - 1][0] + grid[i][0];\n        }\n        for (int i = 1; i < n; i++) {\n            f[0][i] = f[0][i - 1] + grid[0][i];\n        }\n\n        for (int i = 1; i < m; i++) {\n            for (int j = 1; j < n; j++) {\n                f[i][j] = min(f[i - 1][j], f[i][j - 1]) + grid[i][j];\n            }\n        }\n        return f[m - 1][n - 1];\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{动规+滚动数组}\n\\begin{Code}\n// LeetCode, Minimum Path Sum\n// 二维动规+滚动数组\nclass Solution {\npublic:\n    int minPathSum(vector<vector<int> > &grid) {\n        const int m = grid.size();\n        const int n = grid[0].size();\n\n        int f[n];\n        fill(f, f+n, INT_MAX); // 初始值是 INT_MAX，因为后面用了min函数。\n        f[0] = 0;\n\n        for (int i = 0; i < m; i++) {\n            f[0] += grid[i][0];\n            for (int j = 1; j < n; j++) {\n                // 左边的f[j]，表示更新后的f[j]，与公式中的f[i[[j]对应\n                // 右边的f[j]，表示老的f[j]，与公式中的f[i-1][j]对应\n                f[j] = min(f[j - 1], f[j]) + grid[i][j];\n            }\n        }\n        return f[n - 1];\n    }\n};\n\\end{Code}\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Unique Paths, 见 \\S \\ref{sec:unique-paths}\n\\item Unique Paths II, 见 \\S \\ref{sec:unique-paths-ii}\n\\myenddot\n\n\n\\section{Edit Distance} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:edit-distance}\n\n\n\\subsubsection{描述}\nGiven two words \\fn{word1} and \\fn{word2}, find the minimum number of steps required to convert \\fn{word1} to \\fn{word2}. (each operation is counted as 1 step.)\n\nYou have the following 3 operations permitted on a word:\n\\begindot\n\\item Insert a character\n\\item Delete a character\n\\item Replace a character\n\\myenddot\n\n\n\\subsubsection{分析}\n设状态为\\fn{f[i][j]}，表示\\fn{A[0,i]}和\\fn{B[0,j]}之间的最小编辑距离。设\\fn{A[0,i]}的形式是\\fn{str1c}，\\fn{B[0,j]}的形式是\\fn{str2d}，\n\\begin{enumerate}\n\\item 如果\\fn{c==d}，则\\fn{f[i][j]=f[i-1][j-1]}；\n\\item 如果\\fn{c!=d}，\n    \\begin{enumerate}\n        \\item 如果将c替换成d，则\\fn{f[i][j]=f[i-1][j-1]+1}；\n        \\item 如果在c后面添加一个d，则\\fn{f[i][j]=f[i][j-1]+1}；\n        \\item 如果将c删除，则\\fn{f[i][j]=f[i-1][j]+1}；\n    \\end{enumerate}\n\\end{enumerate}\n\n\n\\subsubsection{动规}\n\\begin{Code}\n// LeetCode, Edit Distance\n// 二维动规，时间复杂度O(n*m)，空间复杂度O(n*m)\nclass Solution {\npublic:\n    int minDistance(const string &word1, const string &word2) {\n        const size_t n = word1.size();\n        const size_t m = word2.size();\n        // 长度为n的字符串，有n+1个隔板\n        int f[n + 1][m + 1];\n        for (size_t i = 0; i <= n; i++)\n            f[i][0] = i;\n        for (size_t j = 0; j <= m; j++)\n            f[0][j] = j;\n\n        for (size_t i = 1; i <= n; i++) {\n            for (size_t j = 1; j <= m; j++) {\n                if (word1[i - 1] == word2[j - 1])\n                    f[i][j] = f[i - 1][j - 1];\n                else {\n                    int mn = min(f[i - 1][j], f[i][j - 1]);\n                    f[i][j] = 1 + min(f[i - 1][j - 1], mn);\n                }\n            }\n        }\n        return f[n][m];\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{动规+滚动数组}\n\\begin{Code}\n// LeetCode, Edit Distance\n// 二维动规+滚动数组\n// 时间复杂度O(n*m)，空间复杂度O(n)\nclass Solution {\npublic:\n    int minDistance(const string &word1, const string &word2) {\n        if (word1.length() < word2.length())\n            return minDistance(word2, word1);\n\n        int f[word2.length() + 1];\n        int upper_left = 0; // 额外用一个变量记录f[i-1][j-1]\n\n        for (size_t i = 0; i <= word2.size(); ++i)\n            f[i] = i;\n\n        for (size_t i = 1; i <= word1.size(); ++i) {\n            upper_left = f[0];\n            f[0] = i;\n\n            for (size_t j = 1; j <= word2.size(); ++j) {\n                int upper = f[j];\n\n                if (word1[i - 1] == word2[j - 1])\n                    f[j] = upper_left;\n                else\n                    f[j] = 1 + min(upper_left, min(f[j], f[j - 1]));\n\n                upper_left = upper;\n            }\n        }\n\n        return f[word2.length()];\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item 无\n\\myenddot\n\n\n\\section{Decode Ways} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:decode-ways}\n\n\n\\subsubsection{描述}\nA message containing letters from \\fn{A-Z} is being encoded to numbers using the following mapping:\n\\begin{Code}\n'A' -> 1\n'B' -> 2\n...\n'Z' -> 26\n\\end{Code}\n\nGiven an encoded message containing digits, determine the total number of ways to decode it.\n\nFor example,\nGiven encoded message \\fn{\"12\"}, it could be decoded as \\fn{\"AB\"} (1 2) or \\fn{\"L\"} (12).\n\nThe number of ways decoding \\fn{\"12\"} is 2.\n\n\n\\subsubsection{分析}\n跟 Climbing Stairs (见 \\S \\ref{sec:climbing-stairs})很类似，不过多加一些判断逻辑。\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Decode Ways\n// 动规，时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    int numDecodings(const string &s) {\n        if (s.empty() || s[0] == '0') return 0;\n\n        int prev = 0;\n        int cur = 1;\n        // 长度为n的字符串，有 n+1个阶梯\n        for (size_t i = 1; i <= s.size(); ++i) {\n            if (s[i-1] == '0') cur = 0;\n\n            if (i < 2 || !(s[i - 2] == '1' ||\n                     (s[i - 2] == '2' && s[i - 1] <= '6')))\n                prev = 0;\n\n            int tmp = cur;\n            cur = prev + cur;\n            prev = tmp;\n        }\n        return cur;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Climbing Stairs, 见 \\S \\ref{sec:climbing-stairs}\n\\myenddot\n\n\n\\section{Distinct Subsequences} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:distinct-subsequences}\n\n\n\\subsubsection{描述}\nGiven a string $S$ and a string $T$, count the number of distinct subsequences of $T$ in $S$.\n\nA subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, \\fn{\"ACE\"} is a subsequence of \\fn{\"ABCDE\"} while \\fn{\"AEC\"} is not).\n\nHere is an example:\n$S$ = \\fn{\"rabbbit\"}, $T$ = \\fn{\"rabbit\"}\n\nReturn 3.\n\n\n\\subsubsection{分析}\n设状态为$f(i,j)$，表示\\fn{T[0,j]}在\\fn{S[0,i]}里出现的次数。首先，无论\\fn{S[i]}和\\fn{T[j]}是否相等，若不使用\\fn{S[i]}，则$f(i,j)=f(i-1,j)$；若\\fn{S[i]==T[j]}，则可以使用\\fn{S[i]}，此时$f(i,j)=f(i-1,j)+f(i-1, j-1)$。\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Distinct Subsequences\n// 二维动规+滚动数组\n// 时间复杂度O(m*n)，空间复杂度O(n)\nclass Solution {\npublic:\n    int numDistinct(const string &S, const string &T) {\n        vector<int> f(T.size() + 1);\n        f[0] = 1;\n        for (int i = 0; i < S.size(); ++i) {\n            for (int j = T.size() - 1; j >= 0; --j) {\n                f[j + 1] += S[i] == T[j] ? f[j] : 0;\n            }\n        }\n\n        return f[T.size()];\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item 无\n\\myenddot\n\n\n\\section{Word Break} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:word-break}\n\n\n\\subsubsection{描述}\nGiven a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.\n\nFor example, given \\\\\ns = \\fn{\"leetcode\"},\\\\\ndict = \\fn{[\"leet\", \"code\"]}.\n\nReturn true because \\fn{\"leetcode\"} can be segmented as \\fn{\"leet code\"}.\n\n\n\\subsubsection{分析}\n设状态为$f(i)$，表示\\fn{s[0,i]}是否可以分词，则状态转移方程为\n$$\nf(i) = any\\_of(f(j) \\&\\& s[j+1,i] \\in dict),  0 \\leq j < i\n$$\n\n\n\\subsubsection{深搜}\n\\begin{Code}\n// LeetCode, Word Break\n// 深搜，超时\n// 时间复杂度O(2^n)，空间复杂度O(n)\nclass Solution {\npublic:\n    bool wordBreak(string s, unordered_set<string> &dict) {\n        return dfs(s, dict, 0, 0);\n    }\nprivate:\n    static bool dfs(const string &s, unordered_set<string> &dict,\n            size_t start, size_t cur) {\n        if (cur == s.size()) {\n            return dict.find(s.substr(start, cur-start+1)) != dict.end();\n        }\n        if (dfs(s, dict, start, cur+1)) return true;\n        if (dict.find(s.substr(start, cur-start+1)) != dict.end())\n            if (dfs(s, dict, cur+1, cur+1)) return true;\n        return false;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{动规}\n\\begin{Code}\n// LeetCode, Word Break\n// 动规，时间复杂度O(n^2)，空间复杂度O(n)\nclass Solution {\npublic:\n    bool wordBreak(string s, unordered_set<string> &dict) {\n        // 长度为n的字符串有n+1个隔板\n        vector<bool> f(s.size() + 1, false);\n        f[0] = true; // 空字符串\n        for (int i = 1; i <= s.size(); ++i) {\n            for (int j = i - 1; j >= 0; --j) {\n                if (f[j] && dict.find(s.substr(j, i - j)) != dict.end()) {\n                    f[i] = true;\n                    break;\n                }\n            }\n        }\n        return f[s.size()];\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Word Break II, 见 \\S \\ref{sec:word-break-ii}\n\\myenddot\n\n\n\\section{Word Break II} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:word-break-ii}\n\n\n\\subsubsection{描述}\nGiven a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.\n\nReturn all such possible sentences.\n\nFor example, given  \\\\\ns = \\fn{\"catsanddog\"}, \\\\\ndict = \\fn{[\"cat\", \"cats\", \"and\", \"sand\", \"dog\"]}.\n\nA solution is \\fn{[\"cats and dog\", \"cat sand dog\"]}.\n\n\n\\subsubsection{分析}\n在上一题的基础上，要返回解本身。\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Word Break II\n// 动规，时间复杂度O(n^2)，空间复杂度O(n^2)\nclass Solution {\npublic:\n    vector<string> wordBreak(string s, unordered_set<string> &dict) {\n        // 长度为n的字符串有n+1个隔板\n        vector<bool> f(s.length() + 1, false);\n        // prev[i][j]为true，表示s[j, i)是一个合法单词，可以从j处切开\n        // 第一行未用\n        vector<vector<bool> > prev(s.length() + 1, vector<bool>(s.length()));\n        f[0] = true;\n        for (size_t i = 1; i <= s.length(); ++i) {\n            for (int j = i - 1; j >= 0; --j) {\n                if (f[j] && dict.find(s.substr(j, i - j)) != dict.end()) {\n                    f[i] = true;\n                    prev[i][j] = true;\n                }\n            }\n        }\n        vector<string> result;\n        vector<string> path;\n        gen_path(s, prev, s.length(), path, result);\n        return result;\n\n    }\nprivate:\n    // DFS遍历树，生成路径\n    void gen_path(const string &s, const vector<vector<bool> > &prev,\n            int cur, vector<string> &path, vector<string> &result) {\n        if (cur == 0) {\n            string tmp;\n            for (auto iter = path.crbegin(); iter != path.crend(); ++iter)\n                tmp += *iter + \" \";\n            tmp.erase(tmp.end() - 1);\n            result.push_back(tmp);\n        }\n        for (size_t i = 0; i < s.size(); ++i) {\n            if (prev[cur][i]) {\n                path.push_back(s.substr(i, cur - i));\n                gen_path(s, prev, i, path, result);\n                path.pop_back();\n            }\n        }\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Word Break, 见 \\S \\ref{sec:word-break}\n\\myenddot\n"
  },
  {
    "path": "C++/chapGraph.tex",
    "content": "\\chapter{图}\n\n无向图的节点定义如下：\n\\begin{Code}\n// 无向图的节点\nstruct UndirectedGraphNode {\n    int label;\n    vector<UndirectedGraphNode *> neighbors;\n    UndirectedGraphNode(int x) : label(x) {};\n};\n\\end{Code}\n\n\n\\section{Clone Graph} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:clone-graph}\n\n\n\\subsubsection{描述}\nClone an undirected graph. Each node in the graph contains a \\code{label} and a list of its \\code{neighbours}.\n\n\nOJ's undirected graph serialization:\nNodes are labeled uniquely.\n\nWe use \\code{\\#} as a separator for each node, and \\code{,} as a separator for node label and each neighbour of the node.\nAs an example, consider the serialized graph \\code{\\{0,1,2\\#1,2\\#2,2\\}}.\n\nThe graph has a total of three nodes, and therefore contains three parts as separated by \\code{\\#}.\n\\begin{enumerate}\n\\item First node is labeled as 0. Connect node 0 to both nodes 1 and 2.\n\\item Second node is labeled as 1. Connect node 1 to node 2.\n\\item Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle.\n\\end{enumerate}\n\nVisually, the graph looks like the following:\n\\begin{Code}\n       1\n      / \\\n     /   \\\n    0 --- 2\n         / \\\n         \\_/\n\\end{Code}\n\n\n\\subsubsection{分析}\n广度优先遍历或深度优先遍历都可以。\n\n\n\\subsubsection{DFS}\n\\begin{Code}\n// LeetCode, Clone Graph\n// DFS，时间复杂度O(n)，空间复杂度O(n)\nclass Solution {\npublic:\n    UndirectedGraphNode *cloneGraph(const UndirectedGraphNode *node) {\n        if(node == nullptr) return nullptr;\n        // key is original node，value is copied node\n        unordered_map<const UndirectedGraphNode *,\n                            UndirectedGraphNode *> copied;\n        clone(node, copied);\n        return copied[node];\n    }\nprivate:\n    // DFS\n    static UndirectedGraphNode* clone(const UndirectedGraphNode *node,\n            unordered_map<const UndirectedGraphNode *,\n            UndirectedGraphNode *> &copied) {\n        // a copy already exists\n        if (copied.find(node) != copied.end()) return copied[node];\n\n        UndirectedGraphNode *new_node = new UndirectedGraphNode(node->label);\n        copied[node] = new_node;\n        for (auto nbr : node->neighbors)\n            new_node->neighbors.push_back(clone(nbr, copied));\n        return new_node;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{BFS}\n\\begin{Code}\n// LeetCode, Clone Graph\n// BFS，时间复杂度O(n)，空间复杂度O(n)\nclass Solution {\npublic:\n    UndirectedGraphNode *cloneGraph(const UndirectedGraphNode *node) {\n        if (node == nullptr) return nullptr;\n        // key is original node，value is copied node\n        unordered_map<const UndirectedGraphNode *,\n                            UndirectedGraphNode *> copied;\n        // each node in queue is already copied itself\n        // but neighbors are not copied yet\n        queue<const UndirectedGraphNode *> q;\n        q.push(node);\n        copied[node] = new UndirectedGraphNode(node->label);\n        while (!q.empty()) {\n            const UndirectedGraphNode *cur = q.front();\n            q.pop();\n            for (auto nbr : cur->neighbors) {\n                // a copy already exists\n                if (copied.find(nbr) != copied.end()) {\n                    copied[cur]->neighbors.push_back(copied[nbr]);\n                } else {\n                    UndirectedGraphNode *new_node =\n                            new UndirectedGraphNode(nbr->label);\n                    copied[nbr] = new_node;\n                    copied[cur]->neighbors.push_back(new_node);\n                    q.push(nbr);\n                }\n            }\n        }\n        return copied[node];\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item 无\n\\myenddot\n"
  },
  {
    "path": "C++/chapGreedy.tex",
    "content": "\\chapter{贪心法}\n\n\n\\section{Jump Game} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:jump-game}\n\n\n\\subsubsection{描述}\nGiven an array of non-negative integers, you are initially positioned at the first index of the array.\n\nEach element in the array represents your maximum jump length at that position.\n\nDetermine if you are able to reach the last index.\n\nFor example:\n\n\\code{A = [2,3,1,1,4]}, return true.\n\n\\code{A = [3,2,1,0,4]}, return false.\n\n\n\\subsubsection{分析}\n由于每层最多可以跳\\fn{A[i]}步，也可以跳0或1步，因此如果能到达最高层，则说明每一层都可以到达。有了这个条件，说明可以用贪心法。\n\n思路一：正向，从0出发，一层一层网上跳，看最后能不能超过最高层，能超过，说明能到达，否则不能到达。\n\n思路二：逆向，从最高层下楼梯，一层一层下降，看最后能不能下降到第0层。\n\n思路三：如果不敢用贪心，可以用动规，设状态为\\fn{f[i]}，表示从第0层出发，走到\\fn{A[i]}时剩余的最大步数，则状态转移方程为：\n$$\nf[i] = max(f[i-1], A[i-1])-1, i > 0\n$$\n\n\n\\subsubsection{代码1}\n\\begin{Code}\n// LeetCode, Jump Game\n// 思路1，时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    bool canJump(const vector<int>& nums) {\n        int reach = 1; // 最右能跳到哪里\n        for (int i = 0; i < reach && reach < nums.size(); ++i)\n            reach = max(reach,  i + 1 + nums[i]);\n        return reach >= nums.size();\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{代码2}\n\\begin{Code}\n// LeetCode, Jump Game\n// 思路2，时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    bool canJump (const vector<int>& nums) {\n        if (nums.empty()) return true;\n        // 逆向下楼梯，最左能下降到第几层\n        int left_most = nums.size() - 1;\n\n        for (int i = nums.size() - 2; i >= 0; --i)\n            if (i + nums[i] >= left_most)\n                left_most = i;\n\n        return left_most == 0;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{代码3}\n\\begin{Code}\n// LeetCode, Jump Game\n// 思路三，动规，时间复杂度O(n)，空间复杂度O(n)\nclass Solution {\npublic:\n    bool canJump(const vector<int>& nums) {\n        vector<int> f(nums.size(), 0);\n        f[0] = 0;\n        for (int i = 1; i < nums.size(); i++) {\n            f[i] = max(f[i - 1], nums[i - 1]) - 1;\n            if (f[i] < 0) return false;;\n        }\n        return f[nums.size() - 1] >= 0;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Jump Game II ，见 \\S \\ref{sec:jump-game-ii}\n\\myenddot\n\n\n\\section{Jump Game II} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:jump-game-ii}\n\n\n\\subsubsection{描述}\nGiven an array of non-negative integers, you are initially positioned at the first index of the array.\n\nEach element in the array represents your maximum jump length at that position.\n\nYour goal is to reach the last index in the minimum number of jumps.\n\nFor example:\nGiven array \\code{A = [2,3,1,1,4]}\n\nThe 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\n\\subsubsection{分析}\n贪心法。\n\n\n\\subsubsection{代码1}\n\\begin{Code}\n// LeetCode, Jump Game II\n// 时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    int jump(const vector<int>& nums) {\n        int step = 0; // 最小步数\n        int left = 0;\n        int right = 0;  // [left, right]是当前能覆盖的区间\n        if (nums.size() == 1) return 0;\n\n        while (left <= right) { // 尝试从每一层跳最远\n            ++step;\n            const int old_right = right;\n            for (int i = left; i <= old_right; ++i) {\n                int new_right = i + nums[i];\n                if (new_right >= nums.size() - 1) return step;\n\n                if (new_right > right) right = new_right;\n            }\n            left = old_right + 1;\n        }\n        return 0;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{代码2}\n\\begin{Code}\n// LeetCode, Jump Game II\n// 时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    int jump(const vector<int>& nums) {\n        int result = 0;\n        // the maximum distance that has been reached\n        int last = 0;\n        // the maximum distance that can be reached by using \"ret+1\" steps\n        int cur = 0;\n        for (int i = 0; i < nums.size(); ++i) {\n            if (i > last) {\n                last = cur;\n                ++result;\n            }\n            cur = max(cur, i + nums[i]);\n        }\n\n        return result;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Jump Game ，见 \\S \\ref{sec:jump-game}\n\\myenddot\n\n\n\\section{Best Time to Buy and Sell Stock} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:best-time-to-buy-and-sell-stock}\n\n\n\\subsubsection{描述}\nSay you have an array for which the i-th element is the price of a given stock on day i.\n\nIf you were only permitted to complete at    most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.\n\n\n\\subsubsection{分析}\n贪心法，分别找到价格最低和最高的一天，低进高出，注意最低的一天要在最高的一天之前。\n\n把原始价格序列变成差分序列，本题也可以做是最大$m$子段和，$m=1$。\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Best Time to Buy and Sell Stock\n// 时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    int maxProfit(vector<int> &prices) {\n        if (prices.size() < 2) return 0;\n        int profit = 0;  // 差价，也就是利润\n        int cur_min = prices[0]; // 当前最小\n\n        for (int i = 1; i < prices.size(); i++) {\n            profit = max(profit, prices[i] - cur_min);\n            cur_min = min(cur_min, prices[i]);\n        }\n        return profit;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Best Time to Buy and Sell Stock II，见 \\S \\ref{sec:best-time-to-buy-and-sell-stock-ii}\n\\item Best Time to Buy and Sell Stock III，见 \\S \\ref{sec:best-time-to-buy-and-sell-stock-iii}\n\\myenddot\n\n\n\\section{Best Time to Buy and Sell Stock II} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:best-time-to-buy-and-sell-stock-ii}\n\n\n\\subsubsection{描述}\nSay you have an array for which the i-th element is the price of a given stock on day i.\n\nDesign an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).\n\n\n\\subsubsection{分析}\n贪心法，低进高出，把所有正的价格差价相加起来。\n\n把原始价格序列变成差分序列，本题也可以做是最大$m$子段和，$m=$数组长度。\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Best Time to Buy and Sell Stock II\n// 时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    int maxProfit(vector<int> &prices) {\n        int sum = 0;\n        for (int i = 1; i < prices.size(); i++) {\n            int diff = prices[i] - prices[i - 1];\n            if (diff > 0) sum += diff;\n        }\n        return sum;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Best Time to Buy and Sell Stock，见 \\S \\ref{sec:best-time-to-buy-and-sell-stock}\n\\item Best Time to Buy and Sell Stock III，见 \\S \\ref{sec:best-time-to-buy-and-sell-stock-iii}\n\\myenddot\n\n\n\\section{Longest Substring Without Repeating Characters} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:longest-substring-without-repeating-characters}\n\n\n\\subsubsection{描述}\nGiven a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for \\code{\"abcabcbb\"} is \\code{\"abc\"}, which the length is 3. For \\code{\"bbbbb\"} the longest substring is \\code{\"b\"}, with the length of 1.\n\n\n\\subsubsection{分析}\n假设子串里含有重复字符，则父串一定含有重复字符，单个子问题就可以决定父问题，因此可以用贪心法。跟动规不同，动规里，单个子问题只能影响父问题，不足以决定父问题。\n\n从左往右扫描，当遇到重复字母时，以上一个重复字母的\\fn{index+1}，作为新的搜索起始位置，直到最后一个字母，复杂度是$O(n)$。如图~\\ref{fig:longest-substring-without-repeating-characters}所示。\n\n\\begin{center}\n\\includegraphics[width=300pt]{longest-substring-without-repeating-characters.png}\\\\\n\\figcaption{不含重复字符的最长子串}\\label{fig:longest-substring-without-repeating-characters}\n\\end{center}\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Longest Substring Without Repeating Characters\n// 时间复杂度O(n)，空间复杂度O(1)\n// 考虑非字母的情况\nclass Solution {\npublic:\n    int lengthOfLongestSubstring(string s) {\n        const int ASCII_MAX = 255;\n        int last[ASCII_MAX]; // 记录字符上次出现过的位置\n        int start = 0; // 记录当前子串的起始位置\n\n        fill(last, last + ASCII_MAX, -1); // 0也是有效位置，因此初始化为-1\n        int max_len = 0;\n        for (int i = 0; i < s.size(); i++) {\n            if (last[s[i]] >= start) {\n                max_len = max(i - start, max_len);\n                start = last[s[i]] + 1;\n            }\n            last[s[i]] = i;\n        }\n        return max((int)s.size() - start, max_len);  // 别忘了最后一次，例如\"abcd\"\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item 无\n\\myenddot\n\n\n\\section{Container With Most Water}\n\\label{sec:container-with-most-water}\n\n\n\\subsubsection{描述}\nGiven $n$ non-negative integers $a_1, a_2, ..., a_n$, where each represents a point at coordinate $(i, a_i)$. n vertical lines are drawn such that the two endpoints of line $i$ is at $(i, a_i)$ and $(i, 0)$. Find two lines, which together with x-axis forms a container, such that the container contains the most water.\n\nNote: You may not slant the container.\n\n\n\\subsubsection{分析}\n每个容器的面积，取决于最短的木板。\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Container With Most Water\n// 时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    int maxArea(vector<int> &height) {\n        int start = 0;\n        int end = height.size() - 1;\n        int result = INT_MIN;\n        while (start < end) {\n            int area = min(height[end], height[start]) * (end - start);\n            result = max(result, area);\n            if (height[start] <= height[end]) {\n                start++;\n            } else {\n                end--;\n            }\n        }\n        return result;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Trapping Rain Water, 见 \\S \\ref{sec:trapping-rain-water}\n\\item Largest Rectangle in Histogram, 见 \\S \\ref{sec:largest-rectangle-in-histogram}\n\\myenddot\n"
  },
  {
    "path": "C++/chapImplement.tex",
    "content": "\\chapter{细节实现题}\n这类题目不考特定的算法，纯粹考察写代码的熟练度。\n\n\n\\section{Reverse Integer} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:reverse-integer}\n\n\n\\subsubsection{描述}\nReverse digits of an integer.\n\nExample1: x = 123, return 321\n\nExample2: x = -123, return -321\n\n\n\\textbf{Have you thought about this?}\n\nHere are some good questions to ask before coding. Bonus points for you if you have already thought through this!\n\nIf the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.\n\nDid 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\nThrow 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\n\\subsubsection{分析}\n短小精悍的题，代码也可以写的很短小。\n\n\n\\subsubsection{代码}\n\\begin{Code}\n//LeetCode, Reverse Integer\n// 时间复杂度O(logn)，空间复杂度O(1)\n// 考虑 1.负数的情况 2. 溢出的情况(正溢出&&负溢出，比如 x = -2147483648(即-2^31) )\nclass Solution {\npublic:\n    int reverse (int x) {\n        long long r = 0;\n        long long t = x;\n        t = t > 0 ? t : -t;\n        for (; t; t /= 10)\n            r = r * 10 + t % 10;\n\n        bool sign = x > 0 ? false: true;\n        if (r > 2147483647 || (sign && r > 2147483648)) {\n            return 0;\n        } else {\n            if (sign) {\n                return -r;\n            } else {\n                return r;\n            }\n        }\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Palindrome Number, 见 \\S \\ref{sec:palindrome-number}\n\\myenddot\n\n\n\\section{Palindrome Number} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:palindrome-number}\n\n\n\\subsubsection{描述}\nDetermine whether an integer is a palindrome. Do this without extra space.\n\n\\textbf{Some hints:}\n\nCould negative integers be palindromes? (ie, -1)\n\nIf you are thinking of converting the integer to string, note the restriction of using extra space.\n\nYou could also try reversing an integer. However, if you have solved the problem \"Reverse Integer\", you know that the reversed integer might overflow. How would you handle such case?\n\nThere is a more generic way of solving this problem.\n\n\n\\subsubsection{分析}\n首先想到，可以利用上一题，将整数反转，然后与原来的整数比较，是否相等，相等则为 Palindrome 的。可是 reverse()会溢出。\n\n正确的解法是，不断地取第一位和最后一位（10进制下）进行比较，相等则取第二位和倒数第二位，直到完成比较或者中途找到了不一致的位。\n\n\n\\subsubsection{代码}\n\\begin{Code}\n//LeetCode, Palindrome Number\n// 时间复杂度O(1)，空间复杂度O(1)\nclass Solution {\npublic:\n    bool isPalindrome(int x) {\n        if (x < 0) return false;\n        int d = 1; // divisor\n        while (x / d >= 10) d *= 10;\n\n        while (x > 0) {\n            int q = x / d;  // quotient\n            int r = x % 10;   // remainder\n            if (q != r) return false;\n            x = x % d / 10;\n            d /= 100;\n        }\n        return true;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Reverse Integer, 见 \\S \\ref{sec:reverse-integer}\n\\item Valid Palindrome, 见 \\S \\ref{sec:valid-palindrome}\n\\myenddot\n\n\n\\section{Insert Interval} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:insert-interval}\n\n\n\\subsubsection{描述}\nGiven a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).\n\nYou may assume that the intervals were initially sorted according to their start times.\n\nExample 1:\nGiven intervals \\code{[1,3],[6,9]}, insert and merge \\code{[2,5]} in as \\code{[1,5],[6,9]}.\n\nExample 2:\nGiven \\code{[1,2],[3,5],[6,7],[8,10],[12,16]}, insert and merge \\code{[4,9]} in as \\code{[1,2],[3,10],[12,16]}.\n\nThis is because the new interval \\code{[4,9]} overlaps with \\code{[3,5],[6,7],[8,10]}.\n\n\n\\subsubsection{分析}\n无\n\n\n\\subsubsection{代码}\n\\begin{Code}\nstruct 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 \n//LeetCode, Insert Interval\n// 时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) {\n        vector<Interval>::iterator it = intervals.begin();\n        while (it != intervals.end()) {\n            if (newInterval.end < it->start) {\n                intervals.insert(it, newInterval);\n                return intervals;\n            } else if (newInterval.start > it->end) {\n                it++;\n                continue;\n            } else {\n                newInterval.start = min(newInterval.start, it->start);\n                newInterval.end = max(newInterval.end, it->end);\n                it = intervals.erase(it);\n            }\n        }\n        intervals.insert(intervals.end(), newInterval);\n        return intervals;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\n\\begindot\n\\item Merge Intervals，见 \\S \\ref{sec:merge-intervals}\n\\myenddot\n\n\n\\section{Merge Intervals} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:merge-intervals}\n\n\n\\subsubsection{描述}\nGiven a collection of intervals, merge all overlapping intervals.\n\nFor example,\nGiven \\code{[1,3],[2,6],[8,10],[15,18]},\nreturn \\code{[1,6],[8,10],[15,18]}\n\n\n\\subsubsection{分析}\n复用一下Insert Intervals的解法即可，创建一个新的interval集合，然后每次从旧的里面取一个interval出来，然后插入到新的集合中。\n\n\n\\subsubsection{代码}\n\\begin{Code}\nstruct 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 \n//LeetCode, Merge Interval\n//复用一下Insert Intervals的解法即可\n// 时间复杂度O(n1+n2+...)，空间复杂度O(1)\nclass Solution {\npublic:\n    vector<Interval> merge(vector<Interval> &intervals) {\n        vector<Interval> result;\n        for (int i = 0; i < intervals.size(); i++) {\n            insert(result, intervals[i]);\n        }\n        return result;\n    }\nprivate:\n    vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) {\n        vector<Interval>::iterator it = intervals.begin();\n        while (it != intervals.end()) {\n            if (newInterval.end < it->start) {\n                intervals.insert(it, newInterval);\n                return intervals;\n            } else if (newInterval.start > it->end) {\n                it++;\n                continue;\n            } else {\n                newInterval.start = min(newInterval.start, it->start);\n                newInterval.end = max(newInterval.end, it->end);\n                it = intervals.erase(it);\n            }\n        }\n        intervals.insert(intervals.end(), newInterval);\n        return intervals;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\n\\begindot\n\\item Insert Interval，见 \\S \\ref{sec:insert-interval}\n\\myenddot\n\n\n\\section{Minimum Window Substring} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:minimum-window-substring}\n\n\n\\subsubsection{描述}\nGiven a string $S$ and a string $T$, find the minimum window in $S$ which will contain all the characters in $T$ in complexity $O(n)$.\n\nFor example, \\code{S = \"ADOBECODEBANC\", T = \"ABC\"}\n\nMinimum window is \\code{\"BANC\"}.\n\nNote:\n\\begindot\n\\item If there is no such window in $S$ that covers all characters in $T$, return the emtpy string \\code{\"\"}.\n\\item If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in $S$.\n\\myenddot\n\n\n\\subsubsection{分析}\n双指针，动态维护一个区间。尾指针不断往后扫，当扫到有一个窗口包含了所有$T$的字符后，然后再收缩头指针，直到不能再收缩为止。最后记录所有可能的情况中窗口最小的\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Minimum Window Substring\n// 时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    string minWindow(string S, string T) {\n        if (S.empty()) return \"\";\n        if (S.size() < T.size()) return \"\";\n\n        const int ASCII_MAX = 256;\n        int appeared_count[ASCII_MAX];\n        int expected_count[ASCII_MAX];\n        fill(appeared_count, appeared_count + ASCII_MAX, 0);\n        fill(expected_count, expected_count + ASCII_MAX, 0);\n\n        for (size_t i = 0; i < T.size(); i++) expected_count[T[i]]++;\n\n        int minWidth = INT_MAX, min_start = 0;  // 窗口大小，起点\n        int wnd_start = 0;\n        int appeared = 0;  // 完整包含了一个T\n        //尾指针不断往后扫\n        for (size_t wnd_end = 0; wnd_end < S.size(); wnd_end++) {\n            if (expected_count[S[wnd_end]] > 0)  {  // this char is a part of T\n                appeared_count[S[wnd_end]]++;\n                if (appeared_count[S[wnd_end]] <= expected_count[S[wnd_end]])\n                    appeared++;\n            }\n            if (appeared == T.size()) {  // 完整包含了一个T\n                // 收缩头指针\n                while (appeared_count[S[wnd_start]] > expected_count[S[wnd_start]]\n                        || expected_count[S[wnd_start]] == 0) {\n                    appeared_count[S[wnd_start]]--;\n                    wnd_start++;\n                }\n                if (minWidth > (wnd_end - wnd_start + 1)) {\n                    minWidth = wnd_end - wnd_start + 1;\n                    min_start = wnd_start;\n                }\n            }\n        }\n\n        if (minWidth == INT_MAX) return \"\";\n        else return S.substr(min_start, minWidth);\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\n\\begindot\n\\item 无\n\\myenddot\n\n\n\\section{Multiply Strings} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:multiply-strings}\n\n\n\\subsubsection{描述}\nGiven two numbers represented as strings, return multiplication of the numbers as a string.\n\nNote: The numbers can be arbitrarily large and are non-negative.\n\n\n\\subsubsection{分析}\n高精度乘法。\n\n常见的做法是将字符转化为一个int，一一对应，形成一个int数组。但是这样很浪费空间，一个int32的最大值是$2^{31}-1=2147483647$，可以与9个字符对应，由于有乘法，减半，则至少可以与4个字符一一对应。一个int64可以与9个字符对应。\n\n\n\\subsubsection{代码1}\n\\begin{Code}\n// LeetCode, Multiply Strings\n// @author 连城 (http://weibo.com/lianchengzju)\n// 一个字符对应一个int\n// 时间复杂度O(n*m)，空间复杂度O(n+m)\ntypedef vector<int> bigint;\n\nbigint make_bigint(string const& repr) {\n    bigint n;\n    transform(repr.rbegin(), repr.rend(), back_inserter(n),\n            [](char c) { return c - '0'; });\n    return n;\n}\n\nstring to_string(bigint const& n) {\n    string str;\n    transform(find_if(n.rbegin(), prev(n.rend()),\n            [](char c) { return c > '\\0'; }), n.rend(), back_inserter(str),\n            [](char c) { return c + '0'; });\n    return str;\n}\n\nbigint operator*(bigint const& x, bigint const& y) {\n    bigint z(x.size() + y.size());\n\n    for (size_t i = 0; i < x.size(); ++i)\n        for (size_t j = 0; j < y.size(); ++j) {\n            z[i + j] += x[i] * y[j];\n            z[i + j + 1] += z[i + j] / 10;\n            z[i + j] %= 10;\n        }\n\n    return z;\n}\n\nclass Solution {\npublic:\n    string multiply(string num1, string num2) {\n        return to_string(make_bigint(num1) * make_bigint(num2));\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{代码2}\n\\begin{Code}\n// LeetCode, Multiply Strings\n// 9个字符对应一个int64_t\n// 时间复杂度O(n*m/81)，空间复杂度O((n+m)/9)\n/** 大整数类. */\nclass BigInt {\npublic:\n    /**\n     * @brief 构造函数，将字符串转化为大整数.\n     * @param[in] s 输入的字符串\n     * @return 无\n     */\n    BigInt(string s) {\n        vector<int64_t> result;\n        result.reserve(s.size() / RADIX_LEN + 1);\n\n        for (int i = s.size(); i > 0; i -= RADIX_LEN) {  // [i-RADIX_LEN, i)\n            int temp = 0;\n            const int low = max(i - RADIX_LEN, 0);\n            for (int j = low; j < i; j++) {\n                temp = temp * 10 + s[j] - '0';\n            }\n            result.push_back(temp);\n        }\n        elems = result;\n    }\n    /**\n     * @brief 将整数转化为字符串.\n     * @return 字符串\n     */\n    string toString() {\n        stringstream result;\n        bool started = false; // 用于跳过前导0\n        for (auto i = elems.rbegin(); i != elems.rend(); i++) {\n            if (started) { // 如果多余的0已经都跳过，则输出\n                result << setw(RADIX_LEN) << setfill('0') << *i;\n            } else {\n                result << *i;\n                started = true; // 碰到第一个非0的值，就说明多余的0已经都跳过\n            }\n        }\n\n        if (!started) return \"0\"; // 当x全为0时\n        else return result.str();\n    }\n\n    /**\n     * @brief 大整数乘法.\n     * @param[in] x x\n     * @param[in] y y\n     * @return 大整数\n     */\n    static BigInt multiply(const BigInt &x, const BigInt &y) {\n        vector<int64_t> z(x.elems.size() + y.elems.size(), 0);\n\n        for (size_t i = 0; i < y.elems.size(); i++) {\n            for (size_t j = 0; j < x.elems.size(); j++) { // 用y[i]去乘以x的各位\n                //  两数第i, j位相乘，累加到结果的第i+j位\n                z[i + j] += y.elems[i] * x.elems[j];\n\n                if (z[i + j] >= BIGINT_RADIX) { //  看是否要进位\n                    z[i + j + 1] += z[i + j] / BIGINT_RADIX; //  进位\n                    z[i + j] %= BIGINT_RADIX;\n                }\n            }\n        }\n        while (z.back() == 0) z.pop_back();  // 没有进位，去掉最高位的0\n        return BigInt(z);\n    }\n\nprivate:\n    typedef long long int64_t;\n    /** 一个数组元素对应9个十进制位，即数组是亿进制的\n     * 因为 1000000000 * 1000000000 没有超过 2^63-1\n     */\n    const static int BIGINT_RADIX = 1000000000;\n    const static int RADIX_LEN = 9;\n    /** 万进制整数. */\n    vector<int64_t> elems;\n    BigInt(const vector<int64_t> num) : elems(num) {}\n};\n\n\nclass Solution {\npublic:\n    string multiply(string num1, string num2) {\n        BigInt x(num1);\n        BigInt y(num2);\n        return BigInt::multiply(x, y).toString();\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\n\\begindot\n\\item 无\n\\myenddot\n\n\n\\section{Substring with Concatenation of All Words} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:substring-with-concatenation-of-all-words}\n\n\n\\subsubsection{描述}\nYou are given a string, $S$, and a list of words, $L$, that are all of the same length. Find all starting indices of substring(s) in $S$ that is a concatenation of each word in $L$ exactly once and without any intervening characters.\n\nFor example, given: \n\\begin{Code}\nS: \"barfoothefoobarman\"\nL: [\"foo\", \"bar\"]\n\\end{Code}\n\nYou should return the indices: \\code{[0,9]}.(order does not matter).\n\n\n\\subsubsection{分析}\n无\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Substring with Concatenation of All Words\n// 时间复杂度O(n*m)，空间复杂度O(m)\nclass Solution {\npublic:\n    vector<int> findSubstring(string s, vector<string>& dict) {\n        size_t wordLength = dict.front().length();\n        size_t catLength = wordLength * dict.size();\n        vector<int> result;\n\n        if (s.length() < catLength) return result;\n\n        unordered_map<string, int> wordCount;\n\n        for (auto const& word : dict) ++wordCount[word];\n\n        for (auto i = begin(s); i <= prev(end(s), catLength); ++i) {\n            unordered_map<string, int> unused(wordCount);\n\n            for (auto j = i; j != next(i, catLength); j += wordLength) {\n                auto pos = unused.find(string(j, next(j, wordLength)));\n\n                if (pos == unused.end() || pos->second == 0) break;\n\n                if (--pos->second == 0) unused.erase(pos);\n            }\n\n            if (unused.size() == 0) result.push_back(distance(begin(s), i));\n        }\n\n        return result;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\n\\begindot\n\\item 无\n\\myenddot\n\n\n\\section{Pascal's Triangle} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:pascal-s-triangle}\n\n\n\\subsubsection{描述}\nGiven $numRows$, generate the first $numRows$ of Pascal's triangle.\n\nFor example, given $numRows = 5$,\n\nReturn\n\\begin{Code}\n[\n     [1],\n    [1,1],\n   [1,2,1],\n  [1,3,3,1],\n [1,4,6,4,1]\n]\n\\end{Code}\n\n\n\\subsubsection{分析}\n本题可以用队列，计算下一行时，给上一行左右各加一个0，然后下一行的每个元素，就等于左上角和右上角之和。\n\n另一种思路，下一行第一个元素和最后一个元素赋值为1，中间的每个元素，等于上一行的左上角和右上角元素之和。\n\n\n\\subsubsection{从左到右}\n\\begin{Code}\n// LeetCode, Pascal's Triangle\n// 时间复杂度O(n^2)，空间复杂度O(n)\nclass Solution {\npublic:\n    vector<vector<int> > generate(int numRows) {\n        vector<vector<int> > result;\n        if(numRows == 0) return result;\n\n        result.push_back(vector<int>(1,1)); //first row\n\n        for(int i = 2; i <= numRows; ++i) {\n            vector<int> current(i,1);  // 本行\n            const vector<int> &prev = result[i-2];  // 上一行\n\n            for(int j = 1; j < i - 1; ++j) {\n                current[j] = prev[j-1] + prev[j]; // 左上角和右上角之和\n            }\n            result.push_back(current);\n        }\n        return result;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{从右到左}\n\\begin{Code}\n// LeetCode, Pascal's Triangle\n// 时间复杂度O(n^2)，空间复杂度O(n)\nclass Solution {\npublic:\n    vector<vector<int> > generate(int numRows) {\n        vector<vector<int> > result;\n        vector<int> array;\n        for (int i = 1; i <= numRows; i++) {\n            for (int j = i - 2; j > 0; j--) {\n                array[j] = array[j - 1] + array[j];\n            }\n            array.push_back(1);\n            result.push_back(array);\n        }\n        return result;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Pascal's Triangle II，见 \\S \\ref{sec:pascals-triangle-ii}\n\\myenddot\n\n\n\\section{Pascal's Triangle II} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:pascal-s-triangle-ii}\n\n\n\\subsubsection{描述}\nGiven an index $k$, return the $k^{th}$ row of the Pascal's triangle.\n\nFor example, given $k = 3$,\n\nReturn \\code{[1,3,3,1]}.\n\nNote: Could you optimize your algorithm to use only $O(k)$ extra space?\n\n\n\\subsubsection{分析}\n滚动数组。\n\n\n\\subsubsection{代码}\n\n\\begin{Code}\n// LeetCode, Pascal's Triangle II\n// 滚动数组，时间复杂度O(n^2)，空间复杂度O(n)\nclass Solution {\npublic:\n\tvector<int> getRow(int rowIndex) {\n\t\tvector<int> array;\n\t\tfor (int i = 0; i <= rowIndex; i++) {\n\t\t\tfor (int j = i - 1; j > 0; j--){\n\t\t\t\tarray[j] = array[j - 1] + array[j];\n\t\t\t}\n\t\t\tarray.push_back(1);\n\t\t}\n\t\treturn array;\n\t}\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Pascal's Triangle，见 \\S \\ref{sec:pascals-triangle}\n\\myenddot\n\n\n\\section{Spiral Matrix} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:spiral-matrix}\n\n\n\\subsubsection{描述}\nGiven a matrix of $m \\times n$ elements ($m$ rows, $n$ columns), return all elements of the matrix in spiral order.\n\nFor example,\nGiven the following matrix:\n\\begin{Code}\n[\n [ 1, 2, 3 ],\n [ 4, 5, 6 ],\n [ 7, 8, 9 ]\n]\n\\end{Code}\nYou should return \\fn{[1,2,3,6,9,8,7,4,5]}.\n\n\n\\subsubsection{分析}\n模拟。\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Spiral Matrix\n// @author 龚陆安 (http://weibo.com/luangong)\n// 时间复杂度O(n^2)，空间复杂度O(1)\nclass Solution {\npublic:\n    vector<int> spiralOrder(vector<vector<int> >& matrix) {\n        vector<int> result;\n        if (matrix.empty()) return result;\n        int beginX = 0, endX = matrix[0].size() - 1;\n        int beginY = 0, endY = matrix.size() - 1;\n        while (true) {\n            // From left to right\n            for (int j = beginX; j <= endX; ++j) result.push_back(matrix[beginY][j]);\n            if (++beginY > endY) break;\n            // From top to bottom\n            for (int i = beginY; i <= endY; ++i) result.push_back(matrix[i][endX]);\n            if (beginX > --endX) break;\n            // From right to left\n            for (int j = endX; j >= beginX; --j) result.push_back(matrix[endY][j]);\n            if (beginY > --endY) break;\n            // From bottom to top\n            for (int i = endY; i >= beginY; --i) result.push_back(matrix[i][beginX]);\n            if (++beginX > endX) break;\n        }\n        return result;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Spiral Matrix II ，见 \\S \\ref{sec:spiral-matrix-ii}\n\\myenddot\n\n\n\\section{Spiral Matrix II} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:spiral-matrix-ii}\n\n\n\\subsubsection{描述}\nGiven an integer $n$, generate a square matrix filled with elements from 1 to $n^2$ in spiral order.\n\nFor example,\nGiven $n = 3$,\n\nYou should return the following matrix:\n\\begin{Code}\n[\n [ 1, 2, 3 ],\n [ 8, 9, 4 ],\n [ 7, 6, 5 ]\n]\n\\end{Code}\n\n\n\\subsubsection{分析}\n这题比上一题要简单。\n\n\n\\subsubsection{代码1}\n\\begin{Code}\n// LeetCode, Spiral Matrix II\n// 时间复杂度O(n^2)，空间复杂度O(n^2)\nclass Solution {\npublic:\n    vector<vector<int> > generateMatrix(int n) {\n        vector<vector<int> > matrix(n, vector<int>(n));\n        int begin = 0, end = n - 1;\n        int num = 1;\n\n        while (begin < end) {\n            for (int j = begin; j < end; ++j) matrix[begin][j] = num++;\n            for (int i = begin; i < end; ++i) matrix[i][end] = num++;\n            for (int j = end; j > begin; --j) matrix[end][j] = num++;\n            for (int i = end; i > begin; --i) matrix[i][begin] = num++;\n            ++begin;\n            --end;\n        }\n\n        if (begin == end) matrix[begin][begin] = num;\n\n        return matrix;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{代码2}\n\\begin{Code}\n// LeetCode, Spiral Matrix II\n// @author 龚陆安 (http://weibo.com/luangong)\n// 时间复杂度O(n^2)，空间复杂度O(n^2)\nclass Solution {\npublic:\n    vector<vector<int> > generateMatrix(int n) {\n        vector< vector<int> > matrix(n, vector<int>(n));\n        if (n == 0) return matrix;\n        int beginX = 0, endX = n - 1;\n        int beginY = 0, endY = n - 1;\n        int num = 1;\n        while (true) {\n            for (int j = beginX; j <= endX; ++j) matrix[beginY][j] = num++;\n            if (++beginY > endY) break;\n\n            for (int i = beginY; i <= endY; ++i) matrix[i][endX] = num++;\n            if (beginX > --endX) break;\n\n            for (int j = endX; j >= beginX; --j) matrix[endY][j] = num++;\n            if (beginY > --endY) break;\n\n            for (int i = endY; i >= beginY; --i) matrix[i][beginX] = num++;\n            if (++beginX > endX) break;\n        }\n        return matrix;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Spiral Matrix, 见 \\S \\ref{sec:spiral-matrix}\n\\myenddot\n\n\n\\section{ZigZag Conversion} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:zigzag-conversion}\n\n\n\\subsubsection{描述}\nThe string \\code{\"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\\begin{Code}\nP   A   H   N\nA P L S I I G\nY   I   R\n\\end{Code}\n\nAnd then read line by line: \\code{\"PAHNAPLSIIGYIR\"}\n\nWrite the code that will take a string and make this conversion given a number of rows:\n\\begin{Code}\nstring convert(string text, int nRows);\n\\end{Code}\n\\code{convert(\"PAYPALISHIRING\", 3)} should return \\code{\"PAHNAPLSIIGYIR\"}.\n\n\n\\subsubsection{分析}\n要找到数学规律。真正面试中，不大可能出这种问题。\n\nn=4:\n\\begin{Code}\nP     I     N\nA   L S   I G\nY A   H R\nP     I\n\\end{Code}\n\nn=5:\n\\begin{Code}\nP       H\nA     S I\nY   I   R\nP L     I  G\nA       N\n\\end{Code}\n\n所以，对于每一层垂直元素的坐标 $(i,j)= (j+1 )*n +i$；对于每两层垂直元素之间的插入元素（斜对角元素），$(i,j)= (j+1)*n -i$\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, ZigZag Conversion\n// 时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    string convert(string s, int nRows) {\n        if (nRows <= 1 || s.size() <= 1) return s;\n        string result;\n        for (int i = 0; i < nRows; i++) {\n            for (int j = 0, index = i; index < s.size();\n                    j++, index = (2 * nRows - 2) * j + i) {\n                result.append(1, s[index]);  // 垂直元素\n                if (i == 0 || i == nRows - 1) continue;   // 斜对角元素\n                if (index + (nRows - i - 1) * 2 < s.size())\n                    result.append(1, s[index + (nRows - i - 1) * 2]);\n            }\n        }\n        return result;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item 无\n\\myenddot\n\n\n\\section{Divide Two Integers} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:divide-two-integers}\n\n\n\\subsubsection{描述}\nDivide two integers without using multiplication, division and mod operator.\n\n\n\\subsubsection{分析}\n不能用乘、除和取模，那剩下的，还有加、减和位运算。\n\n最简单的方法，是不断减去被除数。在这个基础上，可以做一点优化，每次把被除数翻倍，从而加速。\n\n\n\\subsubsection{代码1}\n\\begin{Code}\n// LeetCode, Divide Two Integers\n// 时间复杂度O(logn)，空间复杂度O(1)\nclass Solution {\npublic:\n    int divide(int dividend, int divisor) {\n        // 当 dividend = INT_MIN时，-dividend会溢出，所以用 long long\n        long long a = dividend >= 0 ? dividend : -(long long)dividend;\n        long long b = divisor >= 0 ? divisor : -(long long)divisor;\n\n        // 当 dividend = INT_MIN时，divisor = -1时，结果会溢出，所以用 long long\n        long long result = 0;\n        while (a >= b) {\n            long long c = b;\n            for (int i = 0; a >= c; ++i, c <<= 1) {\n                a -= c;\n                result += 1 << i;\n            }\n        }\n\n        return ((dividend^divisor) >> 31) ? (-result) : (result);\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{代码2}\n\\begin{Code}\n// LeetCode, Divide Two Integers\n// 时间复杂度O(logn)，空间复杂度O(1)\nclass Solution {\npublic:\n    int divide(int dividend, int divisor) {\n        int result = 0; // 当 dividend = INT_MIN时，divisor = -1时，结果会溢出\n        const bool sign = (dividend > 0 && divisor < 0) ||\n                (dividend < 0 && divisor > 0); // 异号\n\n        // 当 dividend = INT_MIN时，-dividend会溢出，所以用 unsigned int\n        unsigned int a = dividend >= 0 ? dividend : -dividend;\n        unsigned int b = divisor >= 0 ? divisor : -divisor;\n\n        while (a >= b) {\n            int multi = 1;\n            unsigned int bb = b;\n            while (a >= bb) {\n                a -= bb;\n                result += multi;\n\n                if (bb < INT_MAX >> 1) { // 防止溢出\n                    bb += bb;\n                    multi += multi;\n                }\n            }\n        }\n        if (sign) return -result;\n        else return result;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item 无\n\\myenddot\n\n\n\\section{Text Justification} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:text-justification}\n\n\n\\subsubsection{描述}\nGiven an array of words and a length $L$, format the text such that each line has exactly $L$ characters and is fully (left and right) justified.\n\nYou should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces \\fn{' '} when necessary so that each line has exactly $L$ characters.\n\nExtra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.\n\nFor the last line of text, it should be left justified and no extra space is inserted between words.\n\nFor example, \\\\\nwords: \\code{[\"This\", \"is\", \"an\", \"example\", \"of\", \"text\", \"justification.\"]} \\\\\nL: 16.\n\nReturn the formatted lines as:\n\\begin{Code}\n[\n   \"This    is    an\",\n   \"example  of text\",\n   \"justification.  \"\n]\n\\end{Code}\n\nNote: Each word is guaranteed not to exceed $L$ in length.\n\nCorner Cases:\n\\begindot\n\\item A line other than the last line might contain only one word. What should you do in this case?\n\\item In this case, that line should be left\n\\myenddot\n\n\n\\subsubsection{分析}\n无\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Text Justification\n// 时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    vector<string> fullJustify(vector<string> &words, int L) {\n        vector<string> result;\n        const int n = words.size();\n        int begin = 0, len = 0; // 当前行的起点，当前长度\n        for (int i = 0; i < n; ++i) {\n            if (len + words[i].size() + (i - begin) > L) {\n                result.push_back(connect(words, begin, i - 1, len, L, false));\n                begin = i;\n                len = 0;\n            }\n            len += words[i].size();\n        }\n        // 最后一行不足L\n        result.push_back(connect(words, begin, n - 1, len, L, true));\n        return result;\n    }\n    /**\n     * @brief 将 words[begin, end] 连成一行\n     * @param[in] words 单词列表\n     * @param[in] begin 开始\n     * @param[in] end 结束\n     * @param[in] len words[begin, end]所有单词加起来的长度\n     * @param[in] L 题目规定的一行长度\n     * @param[in] is_last 是否是最后一行\n     * @return 对齐后的当前行\n     */\n    string connect(vector<string> &words, int begin, int end,\n            int len, int L, bool is_last) {\n        string s;\n        int n = end - begin + 1;\n        for (int i = 0; i < n; ++i) {\n            s += words[begin + i];\n            addSpaces(s, i, n - 1, L - len, is_last);\n        }\n\n        if (s.size() < L) s.append(L - s.size(), ' ');\n        return s;\n    }\n\n    /**\n     * @brief 添加空格.\n     * @param[inout]s 一行\n     * @param[in] i 当前空隙的序号\n     * @param[in] n 空隙总数\n     * @param[in] L 总共需要添加的空额数\n     * @param[in] is_last 是否是最后一行\n     * @return 无\n     */\n    void addSpaces(string &s, int i, int n, int L, bool is_last) {\n        if (n < 1 || i > n - 1) return;\n        int spaces = is_last ? 1 : (L / n + (i < (L % n) ? 1 : 0));\n        s.append(spaces, ' ');\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item 无\n\\myenddot\n\n\n\\section{Max Points on a Line} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:max-points-on-a-line}\n\n\n\\subsubsection{描述}\nGiven $n$ points on a 2D plane, find the maximum number of points that lie on the same straight line.\n\n\n\\subsubsection{分析}\n暴力枚举法。两点决定一条直线，$n$个点两两组合，可以得到$\\dfrac{1}{2}n(n+1)$条直线，对每一条直线，判断$n$个点是否在该直线上，从而可以得到这条直线上的点的个数，选择最大的那条直线返回。复杂度$O(n^3)$。\n\n上面的暴力枚举法以“边”为中心，再看另一种暴力枚举法，以每个“点”为中心，然后遍历剩余点，找到所有的斜率，如果斜率相同，那么一定共线对每个点，用一个哈希表，key为斜率，value为该直线上的点数，计算出哈希表后，取最大值，并更新全局最大值，最后就是结果。时间复杂度$O(n^2)$，空间复杂度$O(n)$。\n\n\n\\subsubsection{以边为中心}\n\\begin{Code}\n// LeetCode, Max Points on a Line\n// 暴力枚举法，以边为中心，时间复杂度O(n^3)，空间复杂度O(1)\nclass Solution {\npublic:\n    int maxPoints(vector<Point> &points) {\n        if (points.size() < 3) return points.size();\n        int result = 0;\n\n        for (int i = 0; i < points.size() - 1; i++) {\n            for (int j = i + 1; j < points.size(); j++) {\n                int sign = 0;\n                int a, b, c;\n                if (points[i].x == points[j].x) sign = 1;\n                else {\n                    a = points[j].x - points[i].x;\n                    b = points[j].y - points[i].y;\n                    c = a * points[i].y - b * points[i].x;\n                }\n                int count = 0;\n                for (int k = 0; k < points.size(); k++) {\n                    if ((0 == sign && a * points[k].y == c +  b * points[k].x) || \n                        (1 == sign&&points[k].x == points[j].x)) \n                        count++;\n                }\n                if (count > result) result = count;\n            }\n        }\n        return result;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{以点为中心}\n\\begin{Code}\n// LeetCode, Max Points on a Line\n// 暴力枚举，以点为中心，时间复杂度O(n^2)，空间复杂度O(n)\nclass Solution {\npublic:\n    int maxPoints(vector<Point> &points) {\n        if (points.size() < 3) return points.size();\n        int result = 0;\n\n        unordered_map<double, int> slope_count;\n        for (int i = 0; i < points.size()-1; i++) {\n            slope_count.clear();\n            int samePointNum = 0; // 与i重合的点\n            int point_max = 1;    // 和i共线的最大点数\n\n            for (int j = i + 1; j < points.size(); j++) {\n                double slope; // 斜率\n                if (points[i].x == points[j].x) {\n                    slope = std::numeric_limits<double>::infinity();\n                    if (points[i].y == points[j].y) {\n                        ++ samePointNum;\n                        continue;\n                    }\n                } else {\n                    slope = 1.0 * (points[i].y - points[j].y) / \n                        (points[i].x - points[j].x);\n                }\n\n                int count = 0;\n                if (slope_count.find(slope) != slope_count.end())\n                    count = ++slope_count[slope];\n                else {\n                    count = 2;\n                    slope_count[slope] = 2;\n                }\n\n                if (point_max < count) point_max = count;\n            }\n            result = max(result, point_max + samePointNum);\n        }\n        return result;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item 无\n\\myenddot\n"
  },
  {
    "path": "C++/chapLinearList.tex",
    "content": "\\chapter{线性表}\n这类题目考察线性表的操作，例如，数组，单链表，双向链表等。\n\n\n\\section{数组} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\\subsection{Remove Duplicates from Sorted Array}\n\\label{sec:remove-duplicates-from-sorted-array}\n\n\n\\subsubsection{描述}\nGiven a sorted array, remove the duplicates in place such that each element appear only once and return the new length.\n\nDo not allocate extra space for another array, you must do this in place with constant memory.\n\nFor example, Given input array \\code{A = [1,1,2]},\n\nYour function should return length = 2, and A is now \\code{[1,2]}.\n\n\n\\subsubsection{分析}\n无\n\n\n\\subsubsection{代码1}\n\\begin{Code}\n// LeetCode, Remove Duplicates from Sorted Array\n// 时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    int removeDuplicates(vector<int>& nums) {\n        if (nums.empty()) return 0;\n\n        int index = 0;\n        for (int i = 1; i < nums.size(); i++) {\n            if (nums[index] != nums[i])\n                nums[++index] = nums[i];\n        }\n        return index + 1;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{代码2}\n\\begin{Code}\n// LeetCode, Remove Duplicates from Sorted Array\n// 使用STL，时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    int removeDuplicates(vector<int>& nums) {\n        return distance(nums.begin(), unique(nums.begin(), nums.end()));\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{代码3}\n\\begin{Code}\n// LeetCode, Remove Duplicates from Sorted Array\n// 使用STL，时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    int removeDuplicates(vector<int>& nums) {\n        return distance(nums.begin(), removeDuplicates(nums.begin(), nums.end(), nums.begin()));\n    }\n\n    template<typename InIt, typename OutIt>\n    OutIt removeDuplicates(InIt first, InIt last, OutIt output) {\n        while (first != last) {\n            *output++ = *first;\n            first = upper_bound(first, last, *first);\n        }\n\n        return output;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\n\\begindot\n\\item Remove Duplicates from Sorted Array II，见 \\S \\ref{sec:remove-duplicates-from-sorted-array-ii}\n\\myenddot\n\n\n\\subsection{Remove Duplicates from Sorted Array II}\n\\label{sec:remove-duplicates-from-sorted-array-ii}\n\n\n\\subsubsection{描述}\nFollow up for \"Remove Duplicates\":\nWhat if duplicates are allowed at most twice?\n\nFor example,\nGiven sorted array \\code{A = [1,1,1,2,2,3]},\n\nYour function should return length = 5, and A is now \\code{[1,1,2,2,3]}\n\n\n\\subsubsection{分析}\n加一个变量记录一下元素出现的次数即可。这题因为是已经排序的数组，所以一个变量即可解决。如果是没有排序的数组，则需要引入一个hashmap来记录出现次数。\n\n\n\\subsubsection{代码1}\n\\begin{Code}\n// LeetCode, Remove Duplicates from Sorted Array II\n// 时间复杂度O(n)，空间复杂度O(1)\n// @author hex108 (https://github.com/hex108)\nclass Solution {\npublic:\n    int removeDuplicates(vector<int>& nums) {\n        if (nums.size() <= 2) return nums.size();\n\n        int index = 2;\n        for (int i = 2; i < nums.size(); i++){\n            if (nums[i] != nums[index - 2])\n                nums[index++] = nums[i];\n        }\n\n        return index;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{代码2}\n下面是一个更简洁的版本。上面的代码略长，不过扩展性好一些，例如将\\fn{occur < 2}改为\\fn{occur < 3}，就变成了允许重复最多3次。\n\\begin{Code}\n// LeetCode, Remove Duplicates from Sorted Array II\n// @author 虞航仲 (http://weibo.com/u/1666779725)\n// 时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    int removeDuplicates(vector<int>& nums) {\n        const int n = nums.size();\n        int index = 0;\n        for (int i = 0; i < n; ++i) {\n            if (i > 0 && i < n - 1 && nums[i] == nums[i - 1] && nums[i] == nums[i + 1])\n                continue;\n\n            nums[index++] = nums[i];\n        }\n        return index;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\n\\begindot\n\\item Remove Duplicates from Sorted Array，见 \\S \\ref{sec:remove-duplicates-from-sorted-array}\n\\myenddot\n\n\n\\subsection{Search in Rotated Sorted Array}\n\\label{sec:search-in-rotated-sorted-array}\n\n\n\\subsubsection{描述}\nSuppose a sorted array is rotated at some pivot unknown to you beforehand.\n\n(i.e., \\code{0 1 2 4 5 6 7} might become \\code{4 5 6 7 0 1 2}).\n\nYou are given a target value to search. If found in the array return its index, otherwise return -1.\n\nYou may assume no duplicate exists in the array.\n\n\n\\subsubsection{分析}\n二分查找，难度主要在于左右边界的确定。\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Search in Rotated Sorted Array\n// 时间复杂度O(log n)，空间复杂度O(1)\nclass Solution {\npublic:\n    int search(const vector<int>& nums, int target) {\n        int first = 0, last = nums.size();\n        while (first != last) {\n            const int mid = first  + (last - first) / 2;\n            if (nums[mid] == target)\n                return mid;\n            if (nums[first] <= nums[mid]) {\n                if (nums[first] <= target && target < nums[mid])\n                    last = mid;\n                else\n                    first = mid + 1;\n            } else {\n                if (nums[mid] < target && target <= nums[last-1])\n                    first = mid + 1;\n                else\n                    last = mid;\n            }\n        }\n        return -1;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\n\\begindot\n\\item Search in Rotated Sorted Array II，见 \\S \\ref{sec:search-in-rotated-sorted-array-ii}\n\\myenddot\n\n\n\\subsection{Search in Rotated Sorted Array II}\n\\label{sec:search-in-rotated-sorted-array-ii}\n\n\n\\subsubsection{描述}\nFollow up for \"Search in Rotated Sorted Array\": What if \\emph{duplicates} are allowed?\n\nWould this affect the run-time complexity? How and why?\n\nWrite a function to determine if a given target is in the array.\n\n\n\\subsubsection{分析}\n允许重复元素，则上一题中如果\\fn{A[m]>=A[l]},那么\\fn{[l,m]}为递增序列的假设就不能成立了，比如\\code{[1,3,1,1,1]}。\n\n如果\\fn{A[m]>=A[l]}不能确定递增，那就把它拆分成两个条件：\n\\begindot\n\\item 若\\fn{A[m]>A[l]}，则区间\\fn{[l,m]}一定递增\n\\item 若\\fn{A[m]==A[l]} 确定不了，那就\\fn{l++}，往下看一步即可。\n\\myenddot\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Search in Rotated Sorted Array II\n// 时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    bool search(const vector<int>& nums, int target) {\n        int first = 0, last = nums.size();\n        while (first != last) {\n            const int mid = first  + (last - first) / 2;\n            if (nums[mid] == target)\n                return true;\n            if (nums[first] < nums[mid]) {\n                if (nums[first] <= target && target < nums[mid])\n                    last = mid;\n                else\n                    first = mid + 1;\n            } else if (nums[first] > nums[mid]) {\n                if (nums[mid] < target && target <= nums[last-1])\n                    first = mid + 1;\n                else\n                    last = mid;\n            } else\n                //skip duplicate one\n                first++;\n        }\n        return false;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\n\\begindot\n\\item Search in Rotated Sorted Array，见 \\S \\ref{sec:search-in-rotated-sorted-array}\n\\myenddot\n\n\n\\subsection{Median of Two Sorted Arrays}\n\\label{sec:median-of-two-sorted-arrays}\n\n\n\\subsubsection{描述}\nThere are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be $O(\\log (m+n))$.\n\n\n\\subsubsection{分析}\n这是一道非常经典的题。这题更通用的形式是，给定两个已经排序好的数组，找到两者所有元素中第$k$大的元素。\n\n$O(m+n)$的解法比较直观，直接merge两个数组，然后求第$k$大的元素。\n\n不过我们仅仅需要第$k$大的元素，是不需要“排序”这么昂贵的操作的。可以用一个计数器，记录当前已经找到第$m$大的元素了。同时我们使用两个指针\\fn{pA}和\\fn{pB}，分别指向A和B数组的第一个元素，使用类似于merge sort的原理，如果数组A当前元素小，那么\\fn{pA++}，同时\\fn{m++}；如果数组B当前元素小，那么\\fn{pB++}，同时\\fn{m++}。最终当$m$等于$k$的时候，就得到了我们的答案，$O(k)$时间，$O(1)$空间。但是，当$k$很接近$m+n$的时候，这个方法还是$O(m+n)$的。\n\n有没有更好的方案呢？我们可以考虑从$k$入手。如果我们每次都能够删除一个一定在第$k$大元素之前的元素，那么我们需要进行$k$次。但是如果每次我们都删除一半呢？由于A和B都是有序的，我们应该充分利用这里面的信息，类似于二分查找，也是充分利用了“有序”。\n\n假设A和B的元素个数都大于$k/2$，我们将A的第$k/2$个元素（即\\fn{A[k/2-1]}）和B的第$k/2$个元素（即\\fn{B[k/2-1]}）进行比较，有以下三种情况（为了简化这里先假设$k$为偶数，所得到的结论对于$k$是奇数也是成立的）：\n\\begindot\n\\item \\fn{A[k/2-1] == B[k/2-1]}\n\\item \\fn{A[k/2-1] > B[k/2-1]}\n\\item \\fn{A[k/2-1] < B[k/2-1]}\n\\myenddot\n\n如果\\fn{A[k/2-1] < B[k/2-1]}，意味着\\fn{A[0]}到\\fn{A[k/2-1]}的肯定在$A \\cup B$的top k元素的范围内，换句话说，\\fn{A[k/2-1]}不可能大于$A \\cup B$的第$k$大元素。留给读者证明。\n\n因此，我们可以放心的删除A数组的这$k/2$个元素。同理，当\\fn{A[k/2-1] > B[k/2-1]}时，可以删除B数组的$k/2$个元素。\n\n当\\fn{A[k/2-1] == B[k/2-1]}时，说明找到了第$k$大的元素，直接返回\\fn{A[k/2-1]}或\\fn{B[k/2-1]}即可。\n\n因此，我们可以写一个递归函数。那么函数什么时候应该终止呢？\n\\begindot\n\\item 当A或B是空时，直接返回\\fn{B[k-1]}或\\fn{A[k-1]}；\n\\item 当\\fn{k=1}是，返回\\fn{min(A[0], B[0])}；\n\\item 当\\fn{A[k/2-1] == B[k/2-1]}时，返回\\fn{A[k/2-1]}或\\fn{B[k/2-1]}\n\\myenddot\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Median of Two Sorted Arrays\n// 时间复杂度O(log(m+n))，空间复杂度O(log(m+n))\nclass Solution {\npublic:\n    double findMedianSortedArrays(const vector<int>& A, const vector<int>& B) {\n        const int m = A.size();\n        const int n = B.size();\n        int total = m + n;\n        if (total & 0x1)\n            return find_kth(A.begin(), m, B.begin(), n, total / 2 + 1);\n        else\n            return (find_kth(A.begin(), m, B.begin(), n, total / 2)\n                    + find_kth(A.begin(), m, B.begin(), n, total / 2 + 1)) / 2.0;\n    }\nprivate:\n    static int find_kth(std::vector<int>::const_iterator A, int m, \n            std::vector<int>::const_iterator B, int n, int k) {\n        //always assume that m is equal or smaller than n\n        if (m > n) return find_kth(B, n, A, m, k);\n        if (m == 0) return *(B + k - 1);\n        if (k == 1) return min(*A, *B);\n\n        //divide k into two parts\n        int ia = min(k / 2, m), ib = k - ia;\n        if (*(A + ia - 1) < *(B + ib - 1))\n            return find_kth(A + ia, m - ia, B, n, k - ia);\n        else if (*(A + ia - 1) > *(B + ib - 1))\n            return find_kth(A, m, B + ib, n - ib, k - ib);\n        else\n            return A[ia - 1];\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\n\\begindot\n\\item 无\n\\myenddot\n\n\n\\subsection{Longest Consecutive Sequence} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:longest-consecutive-sequence}\n\n\n\\subsubsection{描述}\nGiven an unsorted array of integers, find the length of the longest consecutive elements sequence.\n\nFor example,\nGiven \\code{[100, 4, 200, 1, 3, 2]},\nThe longest consecutive elements sequence is \\code{[1, 2, 3, 4]}. Return its length: 4.\n\nYour algorithm should run in $O(n)$ complexity.\n\n\n\\subsubsection{分析}\n如果允许$O(n \\log n)$的复杂度，那么可以先排序，可是本题要求$O(n)$。\n\n由于序列里的元素是无序的，又要求$O(n)$，首先要想到用哈希表。\n\n用一个哈希表 \\fn{unordered_map<int, bool> used}记录每个元素是否使用，对每个元素，以该元素为中心，往左右扩张，直到不连续为止，记录下最长的长度。\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// Leet Code, Longest Consecutive Sequence\n// 时间复杂度O(n)，空间复杂度O(n)\nclass Solution {\npublic:\n    int longestConsecutive(const vector<int> &nums) {\n        unordered_map<int, bool> used;\n\n        for (auto i : nums) used[i] = false;\n\n        int longest = 0;\n\n        for (auto i : nums) {\n            if (used[i]) continue;\n\n            int length = 1;\n\n            used[i] = true;\n\n            for (int j = i + 1; used.find(j) != used.end(); ++j) {\n                used[j] = true;\n                ++length;\n            }\n\n            for (int j = i - 1; used.find(j) != used.end(); --j) {\n                used[j] = true;\n                ++length;\n            }\n\n            longest = max(longest, length);\n        }\n\n        return longest;\n    }\n};\n\\end{Code}\n\n\\subsubsection{分析2}\n第一直觉是个聚类的操作,应该有union,find的操作.连续序列可以用两端和长度来表示.\n本来用两端就可以表示,但考虑到查询的需求,将两端分别暴露出来.用\\fn{unordered_map<int, int> map}来\n存储.原始思路来自于\\url{http://discuss.leetcode.com/questions/1070/longest-consecutive-sequence}\n\n\\subsubsection{代码}\n\n\\begin{Code}\n// Leet Code, Longest Consecutive Sequence\n// 时间复杂度O(n)，空间复杂度O(n)\n// Author: @advancedxy\nclass Solution {\npublic:\n    int longestConsecutive(vector<int> &nums) {\n        unordered_map<int, int> map;\n        int size = nums.size();\n        int l = 1;\n        for (int i = 0; i < size; i++) {\n            if (map.find(nums[i]) != map.end()) continue;\n            map[nums[i]] = 1;\n            if (map.find(nums[i] - 1) != map.end()) {\n                l = max(l, mergeCluster(map, nums[i] - 1, nums[i]));\n            }\n            if (map.find(nums[i] + 1) != map.end()) {\n                l = max(l, mergeCluster(map, nums[i], nums[i] + 1));\n            }\n        }\n        return size == 0 ? 0 : l;\n    }\n\nprivate:\n    int mergeCluster(unordered_map<int, int> &map, int left, int right) {\n        int upper = right + map[right] - 1;\n        int lower = left - map[left] + 1;\n        int length = upper - lower + 1;\n        map[upper] = length;\n        map[lower] = length;\n        return length;\n    }\n};\n\\end{Code}\n\n\\subsubsection{相关题目}\n\\begindot\n\\item 无\n\\myenddot\n\n\n\\subsection{Two Sum} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:Two-sum}\n\n\n\\subsubsection{描述}\nGiven an array of integers, find two numbers such that they add up to a specific target number.\n\nThe function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.\n\nYou may assume that each input would have exactly one solution.\n\nInput:  \\code{numbers=\\{2, 7, 11, 15\\}, target=9}\n\nOutput: \\code{index1=1, index2=2}\n\n\n\\subsubsection{分析}\n方法1：暴力，复杂度$O(n^2)$，会超时\n\n方法2：hash。用一个哈希表，存储每个数对应的下标，复杂度$O(n)$.\n\n方法3：先排序，然后左右夹逼，排序$O(n\\log n)$，左右夹逼$O(n)$，最终$O(n\\log n)$。但是注意，这题需要返回的是下标，而不是数字本身，因此这个方法行不通。\n\n\n\\subsubsection{代码}\n\\begin{Code}\n//LeetCode, Two Sum\n// 方法2：hash。用一个哈希表，存储每个数对应的下标\n// 时间复杂度O(n)，空间复杂度O(n)\nclass Solution {\npublic:\n    vector<int> twoSum(vector<int> &nums, int target) {\n        unordered_map<int, int> mapping;\n        vector<int> result;\n        for (int i = 0; i < nums.size(); i++) {\n            mapping[nums[i]] = i;\n        }\n        for (int i = 0; i < nums.size(); i++) {\n            const int gap = target - nums[i];\n            if (mapping.find(gap) != mapping.end() && mapping[gap] > i) {\n                result.push_back(i + 1);\n                result.push_back(mapping[gap] + 1);\n                break;\n            }\n        }\n        return result;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item 3Sum, 见 \\S \\ref{sec:3sum}\n\\item 3Sum Closest, 见 \\S \\ref{sec:3sum-closest}\n\\item 4Sum, 见 \\S \\ref{sec:4sum}\n\\myenddot\n\n\n\\subsection{3Sum} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:3sum}\n\n\n\\subsubsection{描述}\nGiven an array $S$ of $n$ integers, are there elements $a, b, c$ in $S$ such that $a + b + c = 0$? Find all unique triplets in the array which gives the sum of zero.\n\nNote:\n\\begindot\n\\item Elements in a triplet $(a,b,c)$ must be in non-descending order. (ie, $a \\leq b \\leq c$)\n\\item The solution set must not contain duplicate triplets.\n\\myenddot\n\nFor example, given array \\code{S = \\{-1 0 1 2 -1 -4\\}}.\n\nA solution set is:\n\\begin{Code}\n(-1, 0, 1)\n(-1, -1, 2)\n\\end{Code}\n\n\n\\subsubsection{分析}\n先排序，然后左右夹逼，复杂度 $O(n^2)$。\n\n这个方法可以推广到$k$-sum，先排序，然后做$k-2$次循环，在最内层循环左右夹逼，时间复杂度是 $O(\\max\\{n \\log n, n^{k-1}\\})$。\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, 3Sum\n// 先排序，然后左右夹逼，注意跳过重复的数，时间复杂度O(n^2)，空间复杂度O(1)\nclass Solution {\n    public:\n    vector<vector<int>> threeSum(vector<int>& nums) {\n        vector<vector<int>> result;\n        if (nums.size() < 3) return result;\n        sort(nums.begin(), nums.end());\n        const int target = 0;\n\t\t\n        auto last = nums.end();\n        for (auto i = nums.begin(); i < last-2; ++i) {\n            auto j = i+1;\n            if (i > nums.begin() && *i == *(i-1)) continue;\n            auto k = last-1;\n            while (j < k) {\n                if (*i + *j + *k < target) {\n                    ++j;\n                    while(*j == *(j - 1) && j < k) ++j;\n                } else if (*i + *j + *k > target) {\n                    --k;\n                    while(*k == *(k + 1) && j < k) --k;\n                } else {\n                    result.push_back({ *i, *j, *k });\n                    ++j;\n                    --k;\n                    while(*j == *(j - 1) && *k == *(k + 1) && j < k) ++j;\n                }\n            }\n        }\n        return result;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Two sum, 见 \\S \\ref{sec:Two-sum}\n\\item 3Sum Closest, 见 \\S \\ref{sec:3sum-closest}\n\\item 4Sum, 见 \\S \\ref{sec:4sum}\n\\myenddot\n\n\\subsection{3Sum Closest} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:3sum-closest}\n\n\n\\subsubsection{描述}\nGiven an array $S$ of $n$ integers, find three integers in $S$ such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.\n\nFor example, given array \\code{S = \\{-1 2 1 -4\\}}, and \\code{target = 1}.\n\nThe sum that is closest to the target is 2. (\\code{-1 + 2 + 1 = 2}).\n\n\n\\subsubsection{分析}\n先排序，然后左右夹逼，复杂度 $O(n^2)$。\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, 3Sum Closest\n// 先排序，然后左右夹逼，时间复杂度O(n^2)，空间复杂度O(1)\nclass Solution {\npublic:\n    int threeSumClosest(vector<int>& nums, int target) {\n        int result = 0;\n        int min_gap = INT_MAX;\n\n        sort(nums.begin(), nums.end());\n\n        for (auto a = nums.begin(); a != prev(nums.end(), 2); ++a) {\n            auto b = next(a);\n            auto c = prev(nums.end());\n\n            while (b < c) {\n                const int sum = *a + *b + *c;\n                const int gap = abs(sum - target);\n\n                if (gap < min_gap) {\n                    result = sum;\n                    min_gap = gap;\n                }\n\n                if (sum < target) ++b;\n                else              --c;\n            }\n        }\n\n        return result;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Two sum, 见 \\S \\ref{sec:Two-sum}\n\\item 3Sum, 见 \\S \\ref{sec:3sum}\n\\item 4Sum, 见 \\S \\ref{sec:4sum}\n\\myenddot\n\n\n\\subsection{4Sum} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:4sum}\n\n\n\\subsubsection{描述}\nGiven an array $S$ of $n$ integers, are there elements $a, b, c$, and $d$ in $S$ such that $a + b + c + d = target$? Find all unique quadruplets in the array which gives the sum of target.\n\nNote:\n\\begindot\n\\item Elements in a quadruplet $(a,b,c,d)$ must be in non-descending order. (ie, $a \\leq b \\leq c \\leq d$)\n\\item The solution set must not contain duplicate quadruplets.\n\\myenddot\n\nFor example, given array \\code{S = \\{1 0 -1 0 -2 2\\}}, and \\code{target = 0}. \n\nA solution set is:\n\\begin{Code}\n(-1,  0, 0, 1)\n(-2, -1, 1, 2)\n(-2,  0, 0, 2)\n\\end{Code}\n\n\n\\subsubsection{分析}\n先排序，然后左右夹逼，复杂度 $O(n^3)$，会超时。\n\n可以用一个hashmap先缓存两个数的和，最终复杂度$O(n^3)$。这个策略也适用于 3Sum 。\n\n\n\\subsubsection{左右夹逼}\n\\begin{Code}\n// LeetCode, 4Sum\n// 先排序，然后左右夹逼，时间复杂度O(n^3)，空间复杂度O(1)\nclass Solution {\npublic:\n    vector<vector<int>> fourSum(vector<int>& nums, int target) {\n        vector<vector<int>> result;\n        if (nums.size() < 4) return result;\n        sort(nums.begin(), nums.end());\n\n        auto last = nums.end();\n        for (auto a = nums.begin(); a < prev(last, 3); ++a) {\n            for (auto b = next(a); b < prev(last, 2); ++b) {\n                auto c = next(b);\n                auto d = prev(last);\n                while (c < d) {\n                    if (*a + *b + *c + *d < target) {\n                        ++c;\n                    } else if (*a + *b + *c + *d > target) {\n                        --d;\n                    } else {\n                        result.push_back({ *a, *b, *c, *d });\n                        ++c;\n                        --d;\n                    }\n                }\n            }\n        }\n        sort(result.begin(), result.end());\n        result.erase(unique(result.begin(), result.end()), result.end());\n        return result;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{map做缓存}\n\\begin{Code}\n// LeetCode, 4Sum\n// 用一个hashmap先缓存两个数的和\n// 时间复杂度，平均O(n^2)，最坏O(n^4)，空间复杂度O(n^2)\nclass Solution {\npublic:\n    vector<vector<int> > fourSum(vector<int> &nums, int target) {\n        vector<vector<int>> result;\n        if (nums.size() < 4) return result;\n        sort(nums.begin(), nums.end());\n\n        unordered_map<int, vector<pair<int, int> > > cache;\n        for (size_t a = 0; a < nums.size(); ++a) {\n            for (size_t b = a + 1; b < nums.size(); ++b) {\n                cache[nums[a] + nums[b]].push_back(pair<int, int>(a, b));\n            }\n        }\n\n        for (int c = 0; c < nums.size(); ++c) {\n            for (size_t d = c + 1; d < nums.size(); ++d) {\n                const int key = target - nums[c] - nums[d];\n                if (cache.find(key) == cache.end()) continue;\n\n                const auto& vec = cache[key];\n                for (size_t k = 0; k < vec.size(); ++k) {\n                    if (c <= vec[k].second)\n                        continue; // 有重叠\n\n                    result.push_back( { nums[vec[k].first],\n                            nums[vec[k].second], nums[c], nums[d] });\n                }\n            }\n        }\n        sort(result.begin(), result.end());\n        result.erase(unique(result.begin(), result.end()), result.end());\n        return result;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{multimap}\n\\begin{Code}\n// LeetCode, 4Sum\n// 用一个 hashmap 先缓存两个数的和\n// 时间复杂度O(n^2)，空间复杂度O(n^2)\n// @author 龚陆安(http://weibo.com/luangong)\nclass Solution {\npublic:\n    vector<vector<int>> fourSum(vector<int>& nums, int target) {\n        vector<vector<int>> result;\n        if (nums.size() < 4) return result;\n        sort(nums.begin(), nums.end());\n\n        unordered_multimap<int, pair<int, int>> cache;\n        for (int i = 0; i + 1 < nums.size(); ++i)\n            for (int j = i + 1; j < nums.size(); ++j)\n                cache.insert(make_pair(nums[i] + nums[j], make_pair(i, j)));\n\n        for (auto i = cache.begin(); i != cache.end(); ++i) {\n            int x = target - i->first;\n            auto range = cache.equal_range(x);\n            for (auto j = range.first; j != range.second; ++j) {\n                auto a = i->second.first;\n                auto b = i->second.second;\n                auto c = j->second.first;\n                auto d = j->second.second;\n                if (a != c && a != d && b != c && b != d) {\n                    vector<int> vec = { nums[a], nums[b], nums[c], nums[d] };\n                    sort(vec.begin(), vec.end());\n                    result.push_back(vec);\n                }\n            }\n        }\n        sort(result.begin(), result.end());\n        result.erase(unique(result.begin(), result.end()), result.end());\n        return result;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{方法4}\n\\begin{Code}\n// LeetCode, 4Sum\n// 先排序，然后左右夹逼，时间复杂度O(n^3logn)，空间复杂度O(1)，会超时\n// 跟方法1相比，表面上优化了，实际上更慢了，切记！\nclass Solution {\npublic:\n    vector<vector<int>> fourSum(vector<int>& nums, int target) {\n        vector<vector<int>> result;\n        if (nums.size() < 4) return result;\n        sort(nums.begin(), nums.end());\n\n        auto last = nums.end();\n        for (auto a = nums.begin(); a < prev(last, 3);\n                a = upper_bound(a, prev(last, 3), *a)) {\n            for (auto b = next(a); b < prev(last, 2);\n                    b = upper_bound(b, prev(last, 2), *b)) {\n                auto c = next(b);\n                auto d = prev(last);\n                while (c < d) {\n                    if (*a + *b + *c + *d < target) {\n                        c = upper_bound(c, d, *c);\n                    } else if (*a + *b + *c + *d > target) {\n                        d = prev(lower_bound(c, d, *d));\n                    } else {\n                        result.push_back({ *a, *b, *c, *d });\n                        c = upper_bound(c, d, *c);\n                        d = prev(lower_bound(c, d, *d));\n                    }\n                }\n            }\n        }\n        return result;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Two sum, 见 \\S \\ref{sec:Two-sum}\n\\item 3Sum, 见 \\S \\ref{sec:3sum}\n\\item 3Sum Closest, 见 \\S \\ref{sec:3sum-closest}\n\\myenddot\n\n\n\\subsection{Remove Element} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:remove-element }\n\n\n\\subsubsection{描述}\nGiven an array and a value, remove all instances of that value in place and return the new length.\n\nThe order of elements can be changed. It doesn't matter what you leave beyond the new length.\n\n\n\\subsubsection{分析}\n无\n\n\n\\subsubsection{代码1}\n\\begin{Code}\n// LeetCode, Remove Element\n// 时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    int removeElement(vector<int>& nums, int target) {\n        int index = 0;\n        for (int i = 0; i < nums.size(); ++i) {\n            if (nums[i] != target) {\n                nums[index++] = nums[i];\n            }\n        }\n        return index;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{代码2}\n\\begin{Code}\n// LeetCode, Remove Element\n// 使用remove()，时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    int removeElement(vector<int>& nums, int target) {\n        return distance(nums.begin(), remove(nums.begin(), nums.end(), target));\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item 无\n\\myenddot\n\n\n\\subsection{Next Permutation} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:next-permutation}\n\n\n\\subsubsection{描述}\nImplement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.\n\nIf such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).\n\nThe replacement must be in-place, do not allocate extra memory.\n\nHere are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.\n\\begin{Code}\n1,2,3 → 1,3,2\n3,2,1 → 1,2,3\n1,1,5 → 1,5,1\n\\end{Code}\n\n\n\\subsubsection{分析}\n算法过程如图~\\ref{fig:permutation}所示（来自\\myurl{http://fisherlei.blogspot.com/2012/12/leetcode-next-permutation.html}）。\n\n\\begin{center}\n\\includegraphics[width=360pt]{next-permutation.png}\\\\\n\\figcaption{下一个排列算法流程}\\label{fig:permutation}\n\\end{center}\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Next Permutation\n// 时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    void nextPermutation(vector<int> &nums) {\n        next_permutation(nums.begin(), nums.end());\n    }\n\n    template<typename BidiIt>\n    bool next_permutation(BidiIt first, BidiIt last) {\n        // Get a reversed range to simplify reversed traversal.\n        const auto rfirst = reverse_iterator<BidiIt>(last);\n        const auto rlast = reverse_iterator<BidiIt>(first);\n\n        // Begin from the second last element to the first element.\n        auto pivot = next(rfirst);\n\n        // Find `pivot`, which is the first element that is no less than its\n        // successor.  `Prev` is used since `pivort` is a `reversed_iterator`.\n        while (pivot != rlast && *pivot >= *prev(pivot))\n            ++pivot;\n\n        // No such elemenet found, current sequence is already the largest\n        // permutation, then rearrange to the first permutation and return false.\n        if (pivot == rlast) {\n            reverse(rfirst, rlast);\n            return false;\n        }\n\n        // Scan from right to left, find the first element that is greater than\n        // `pivot`.\n        auto change = find_if(rfirst, pivot, bind1st(less<int>(), *pivot));\n\n        swap(*change, *pivot);\n        reverse(rfirst, pivot);\n\n        return true;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Permutation Sequence, 见 \\S \\ref{sec:permutation-sequence}\n\\item Permutations, 见 \\S \\ref{sec:permutations}\n\\item Permutations II, 见 \\S \\ref{sec:permutations-ii}\n\\item Combinations, 见 \\S \\ref{sec:combinations}\n\\myenddot\n\n\n\\subsection{Permutation Sequence} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:permutation-sequence}\n\n\n\\subsubsection{描述}\nThe set \\fn{[1,2,3,…,n]} contains a total of $n!$ unique permutations.\n\nBy listing and labeling all of the permutations in order,\nWe get the following sequence (ie, for $n = 3$):\n\\begin{Code}\n\"123\"\n\"132\"\n\"213\"\n\"231\"\n\"312\"\n\"321\"\n\\end{Code}\n\nGiven $n$ and $k$, return the kth permutation sequence.\n\nNote: Given $n$ will be between 1 and 9 inclusive.\n\n\n\\subsubsection{分析}\n简单的，可以用暴力枚举法，调用 $k-1$ 次 \\fn{next_permutation()}。\n\n暴力枚举法把前 $k$个排列都求出来了，比较浪费，而我们只需要第$k$个排列。\n\n利用康托编码的思路，假设有$n$个不重复的元素，第$k$个排列是$a_1, a_2, a_3, ..., a_n$，那么$a_1$是哪一个位置呢？\n\n我们把$a_1$去掉，那么剩下的排列为\n$a_2, a_3, ..., a_n$, 共计$n-1$个元素，$n-1$个元素共有$(n-1)!$个排列，于是就可以知道 $a_1 = k / (n-1)!$。\n\n同理，$a_2, a_3, ..., a_n$的值推导如下：\n\n\\begin{eqnarray}\nk_2 &=& k\\%(n-1)! \\nonumber \\\\\na_2 &=& k_2/(n-2)! \\nonumber \\\\\n\\quad & \\cdots \\nonumber \\\\\nk_{n-1} &=& k_{n-2}\\%2! \\nonumber \\\\\na_{n-1} &=& k_{n-1}/1! \\nonumber \\\\\na_n &=& 0 \\nonumber\n\\end{eqnarray}\n\n\n\\subsubsection{使用next_permutation()}\n\\begin{Code}\n// LeetCode, Permutation Sequence\n// 使用next_permutation()，TLE\nclass Solution {\npublic:\n    string getPermutation(int n, int k) {\n        string s(n, '0');\n        for (int i = 0; i < n; ++i)\n            s[i] += i+1;\n        for (int i = 0; i < k-1; ++i)\n            next_permutation(s.begin(), s.end());\n        return s;\n    }\n\n    template<typename BidiIt>\n    bool next_permutation(BidiIt first, BidiIt last) {\n        // 代码见上一题 Next Permutation\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{康托编码}\n\\begin{Code}\n// LeetCode, Permutation Sequence\n// 康托编码，时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    string getPermutation(int n, int k) {\n        string s(n, '0');\n        string result;\n        for (int i = 0; i < n; ++i)\n            s[i] += i + 1;\n\n        return kth_permutation(s, k);\n    }\nprivate:\n    int factorial(int n) {\n        int result = 1;\n        for (int i = 1; i <= n; ++i)\n            result *= i;\n        return result;\n    }\n\n    // seq 已排好序，是第一个排列\n    template<typename Sequence>\n    Sequence kth_permutation(const Sequence &seq, int k) {\n        const int n = seq.size();\n        Sequence S(seq);\n        Sequence result;\n\n        int base = factorial(n - 1);\n        --k;  // 康托编码从0开始\n\n        for (int i = n - 1; i > 0; k %= base, base /= i, --i) {\n            auto a = next(S.begin(), k / base);\n            result.push_back(*a);\n            S.erase(a);\n        }\n\n        result.push_back(S[0]); // 最后一个\n        return result;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Next Permutation, 见 \\S \\ref{sec:next-permutation}\n\\item Permutations, 见 \\S \\ref{sec:permutations}\n\\item Permutations II, 见 \\S \\ref{sec:permutations-ii}\n\\item Combinations, 见 \\S \\ref{sec:combinations}\n\\myenddot\n\n\n\\subsection{Valid Sudoku} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:valid-sudoku}\n\n\n\\subsubsection{描述}\nDetermine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules \\myurl{http://sudoku.com.au/TheRules.aspx} .\n\nThe Sudoku board could be partially filled, where empty cells are filled with the character \\fn{'.'}.\n\n\\begin{center}\n\\includegraphics[width=150pt]{sudoku.png}\\\\\n\\figcaption{A partially filled sudoku which is valid}\\label{fig:sudoku}\n\\end{center}\n\n\\subsubsection{分析}\n细节实现题。\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Valid Sudoku\n// 时间复杂度O(n^2)，空间复杂度O(1)\nclass Solution {\npublic:\n    bool isValidSudoku(const vector<vector<char>>& board) {\n        bool used[9];\n\n        for (int i = 0; i < 9; ++i) {\n            fill(used, used + 9, false);\n\n            for (int j = 0; j < 9; ++j) // 检查行\n                if (!check(board[i][j], used))\n                    return false;\n\n            fill(used, used + 9, false);\n\n            for (int j = 0; j < 9; ++j) // 检查列\n                if (!check(board[j][i], used))\n                    return false;\n        }\n\n        for (int r = 0; r < 3; ++r) // 检查 9 个子格子\n            for (int c = 0; c < 3; ++c) {\n                fill(used, used + 9, false);\n\n                for (int i = r * 3; i < r * 3 + 3; ++i)\n                    for (int j = c * 3; j < c * 3 + 3; ++j)\n                        if (!check(board[i][j], used))\n                            return false;\n            }\n\n        return true;\n    }\n\n    bool check(char ch, bool used[9]) {\n        if (ch == '.') return true;\n\n        if (used[ch - '1']) return false;\n\n        return used[ch - '1'] = true;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Sudoku Solver, 见 \\S \\ref{sec:sudoku-solver}\n\\myenddot\n\n\n\\subsection{Trapping Rain Water} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:trapping-rain-water}\n\n\n\\subsubsection{描述}\nGiven $n$ non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.\n\nFor example, \nGiven \\code{[0,1,0,2,1,0,1,3,2,1,2,1]}, return 6.\n\n\\begin{center}\n\\includegraphics{trapping-rain-water.png}\\\\\n\\figcaption{Trapping Rain Water}\\label{fig:trapping-rain-water}\n\\end{center}\n\n\n\\subsubsection{分析}\n对于每个柱子，找到其左右两边最高的柱子，该柱子能容纳的面积就是\\code{min(max_left, max_right) - height}。所以，\n\\begin{enumerate}\n\\item 从左往右扫描一遍，对于每个柱子，求取左边最大值；\n\\item 从右往左扫描一遍，对于每个柱子，求最大右值；\n\\item 再扫描一遍，把每个柱子的面积并累加。\n\\end{enumerate}\n\n也可以，\n\\begin{enumerate}\n\\item 扫描一遍，找到最高的柱子，这个柱子将数组分为两半；\n\\item 处理左边一半；\n\\item 处理右边一半。\n\\end{enumerate}\n\n\n\\subsubsection{代码1}\n\\begin{Code}\n// LeetCode, Trapping Rain Water\n// 思路1，时间复杂度O(n)，空间复杂度O(n)\nclass Solution {\npublic:\n    int trap(const vector<int>& A) {\n        const int n = A.size();\n        int *max_left = new int[n]();\n        int *max_right = new int[n]();\n\n        for (int i = 1; i < n; i++) {\n            max_left[i] = max(max_left[i - 1], A[i - 1]);\n            max_right[n - 1 - i] = max(max_right[n - i], A[n - i]);\n\n        }\n\n        int sum = 0;\n        for (int i = 0; i < n; i++) {\n            int height = min(max_left[i], max_right[i]);\n            if (height > A[i]) {\n                sum += height - A[i];\n            }\n        }\n\n        delete[] max_left;\n        delete[] max_right;\n        return sum;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{代码2}\n\\begin{Code}\n// LeetCode, Trapping Rain Water\n// 思路2，时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    int trap(const vector<int>& A) {\n        const int n = A.size();\n        int max = 0; // 最高的柱子，将数组分为两半\n        for (int i = 0; i < n; i++)\n            if (A[i] > A[max]) max = i;\n\n        int water = 0;\n        for (int i = 0, peak = 0; i < max; i++)\n            if (A[i] > peak) peak = A[i];\n            else water += peak - A[i];\n        for (int i = n - 1, top = 0; i > max; i--)\n            if (A[i] > top) top = A[i];\n            else water += top - A[i];\n        return water;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{代码3}\n第三种解法，用一个栈辅助，小于栈顶的元素压入，大于等于栈顶就把栈里所有小于或等于当前值的元素全部出栈处理掉。\n\\begin{Code}\n// LeetCode, Trapping Rain Water\n// 用一个栈辅助，小于栈顶的元素压入，大于等于栈顶就把栈里所有小于或\n// 等于当前值的元素全部出栈处理掉，计算面积，最后把当前元素入栈\n// 时间复杂度O(n)，空间复杂度O(n)\nclass Solution {\npublic:\n    int trap(const vector<int>& A) {\n        const int n = A.size();\n        stack<pair<int, int>> s;\n        int water = 0;\n\n        for (int i = 0; i < n; ++i) {\n            int height = 0;\n\n            while (!s.empty()) { // 将栈里比当前元素矮或等高的元素全部处理掉\n                int bar = s.top().first;\n                int pos = s.top().second;\n                // bar, height, A[i] 三者夹成的凹陷\n                water += (min(bar, A[i]) - height) * (i - pos - 1);\n                height = bar;\n\n                if (A[i] < bar) // 碰到了比当前元素高的，跳出循环\n                    break;\n                else\n                    s.pop(); // 弹出栈顶，因为该元素处理完了，不再需要了\n            }\n\n            s.push(make_pair(A[i], i));\n        }\n\n        return water;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Container With Most Water, 见 \\S \\ref{sec:container-with-most-water}\n\\item Largest Rectangle in Histogram, 见 \\S \\ref{sec:largest-rectangle-in-histogram}\n\\myenddot\n\n\n\\subsection{Rotate Image} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:rotate-image}\n\n\n\\subsubsection{描述}\nYou are given an $n \\times n$ 2D matrix representing an image.\n\nRotate the image by 90 degrees (clockwise).\n\nFollow up:\nCould you do this in-place?\n\n\n\\subsubsection{分析}\n首先想到，纯模拟，从外到内一圈一圈的转，但这个方法太慢。\n\n如下图，首先沿着副对角线翻转一次，然后沿着水平中线翻转一次。\n\n\\begin{center}\n\\includegraphics[width=200pt]{rotate-image.png}\\\\\n\\figcaption{Rotate Image}\\label{fig:rotate-image}\n\\end{center}\n\n或者，首先沿着水平中线翻转一次，然后沿着主对角线翻转一次。\n\n\n\\subsubsection{代码1}\n\\begin{Code}\n// LeetCode, Rotate Image\n// 思路 1，时间复杂度O(n^2)，空间复杂度O(1)\nclass Solution {\npublic:\n    void rotate(vector<vector<int>>& matrix) {\n        const int n = matrix.size();\n\n        for (int i = 0; i < n; ++i)  // 沿着副对角线反转\n            for (int j = 0; j < n - i; ++j)\n                swap(matrix[i][j], matrix[n - 1 - j][n - 1 - i]);\n\n        for (int i = 0; i < n / 2; ++i) // 沿着水平中线反转\n            for (int j = 0; j < n; ++j)\n                swap(matrix[i][j], matrix[n - 1 - i][j]);\n    }\n};\n\\end{Code}\n\n\\subsubsection{代码2}\n\\begin{Code}\n// LeetCode, Rotate Image\n// 思路 2，时间复杂度O(n^2)，空间复杂度O(1)\nclass Solution {\npublic:\n    void rotate(vector<vector<int>>& matrix) {\n        const int n = matrix.size();\n\n        for (int i = 0; i < n / 2; ++i) // 沿着水平中线反转\n            for (int j = 0; j < n; ++j)\n                swap(matrix[i][j], matrix[n - 1 - i][j]);\n\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    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item 无\n\\myenddot\n\n\n\\subsection{Plus One} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:plus-one}\n\n\n\\subsubsection{描述}\nGiven a number represented as an array of digits, plus one to the number.\n\n\n\\subsubsection{分析}\n高精度加法。\n\n\n\\subsubsection{代码1}\n\\begin{Code}\n// LeetCode, Plus One\n// 时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    vector<int> plusOne(vector<int> &digits) {\n        add(digits, 1);\n        return digits;\n    }\nprivate:\n    // 0 <= digit <= 9\n    void add(vector<int> &digits, int digit) {\n        int c = digit;  // carry, 进位\n\n        for (auto it = digits.rbegin(); it != digits.rend(); ++it) {\n            *it += c;\n            c = *it / 10;\n            *it %= 10;\n        }\n\n        if (c > 0) digits.insert(digits.begin(), 1);\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{代码2}\n\\begin{Code}\n// LeetCode, Plus One\n// 时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    vector<int> plusOne(vector<int> &digits) {\n        add(digits, 1);\n        return digits;\n    }\nprivate:\n    // 0 <= digit <= 9\n    void add(vector<int> &digits, int digit) {\n        int c = digit;  // carry, 进位\n\n        for_each(digits.rbegin(), digits.rend(), [&c](int &d){\n            d += c;\n            c = d / 10;\n            d %= 10;\n        });\n\n        if (c > 0) digits.insert(digits.begin(), 1);\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item 无\n\\myenddot\n\n\n\\subsection{Climbing Stairs} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:climbing-stairs}\n\n\n\\subsubsection{描述}\nYou are climbing a stair case. It takes $n$ steps to reach to the top.\n\nEach time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?\n\n\n\\subsubsection{分析}\n设$f(n)$表示爬$n$阶楼梯的不同方法数，为了爬到第$n$阶楼梯，有两个选择：\n\\begindot\n\\item 从第$n-1$阶前进1步；\n\\item 从第$n-1$阶前进2步；\n\\myenddot\n因此，有$f(n)=f(n-1)+f(n-2)$。\n\n这是一个斐波那契数列。\n\n方法1，递归，太慢；方法2，迭代。\n\n方法3，数学公式。斐波那契数列的通项公式为 $a_n=\\dfrac{1}{\\sqrt{5}}\\left[\\left(\\dfrac{1+\\sqrt{5}}{2}\\right)^n-\\left(\\dfrac{1-\\sqrt{5}}{2}\\right)^n\\right]$。\n\n\n\\subsubsection{迭代}\n\\begin{Code}\n// LeetCode, Climbing Stairs\n// 迭代，时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    int climbStairs(int n) {\n        int prev = 0;\n        int cur = 1;\n        for(int i = 1; i <= n ; ++i){\n            int tmp = cur;\n            cur += prev;\n            prev = tmp;\n        }\n        return cur;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{数学公式}\n\\begin{Code}\n// LeetCode, Climbing Stairs\n// 数学公式，时间复杂度O(1)，空间复杂度O(1)\nclass Solution {\n    public:\n    int climbStairs(int n) {\n        const double s = sqrt(5);\n        return floor((pow((1+s)/2, n+1) + pow((1-s)/2, n+1))/s + 0.5);\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Decode Ways, 见 \\S \\ref{sec:decode-ways}\n\\myenddot\n\n\n\\subsection{Gray Code} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:gray-code}\n\n\n\\subsubsection{描述}\nThe gray code is a binary numeral system where two successive values differ in only one bit.\n\nGiven a non-negative integer $n$ representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.\n\nFor example, given $n = 2$, return \\fn{[0,1,3,2]}. Its gray code sequence is:\n\\begin{Code}\n00 - 0\n01 - 1\n11 - 3\n10 - 2\n\\end{Code}\n\nNote:\n\\begindot\n\\item For a given $n$, a gray code sequence is not uniquely defined.\n\\item For example, \\fn{[0,2,3,1]} is also a valid gray code sequence according to the above definition.\n\\item For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that.\n\\myenddot\n\n\n\\subsubsection{分析}\n格雷码(Gray Code)的定义请参考 \\myurl{http://en.wikipedia.org/wiki/Gray_code}\n\n\\textbf{自然二进制码转换为格雷码：$g_0=b_0, g_i=b_i \\oplus b_{i-1}$}\n\n保留自然二进制码的最高位作为格雷码的最高位，格雷码次高位为二进制码的高位与次高位异或，其余各位与次高位的求法类似。例如，将自然二进制码1001，转换为格雷码的过程是：保留最高位；然后将第1位的1和第2位的0异或，得到1，作为格雷码的第2位；将第2位的0和第3位的0异或，得到0，作为格雷码的第3位；将第3位的0和第4位的1异或，得到1，作为格雷码的第4位，最终，格雷码为1101。\n\n\\textbf{格雷码转换为自然二进制码：$b_0=g_0, b_i=g_i \\oplus b_{i-1}$}\n\n保留格雷码的最高位作为自然二进制码的最高位，次高位为自然二进制高位与格雷码次高位异或，其余各位与次高位的求法类似。例如，将格雷码1000转换为自然二进制码的过程是：保留最高位1，作为自然二进制码的最高位；然后将自然二进制码的第1位1和格雷码的第2位0异或，得到1，作为自然二进制码的第2位；将自然二进制码的第2位1和格雷码的第3位0异或，得到1，作为自然二进制码的第3位；将自然二进制码的第3位1和格雷码的第4位0异或，得到1，作为自然二进制码的第4位，最终，自然二进制码为1111。\n\n格雷码有\\textbf{数学公式}，整数$n$的格雷码是$n \\oplus (n/2)$。\n\n这题要求生成$n$比特的所有格雷码。\n\n方法1，最简单的方法，利用数学公式，对从 $0\\sim2^n-1$的所有整数，转化为格雷码。\n\n方法2，$n$比特的格雷码，可以递归地从$n-1$比特的格雷码生成。如图\\S \\ref{fig:gray-code-construction}所示。\n\n\\begin{center}\n\\includegraphics[width=160pt]{gray-code-construction.png}\\\\\n\\figcaption{The first few steps of the reflect-and-prefix method.}\\label{fig:gray-code-construction}\n\\end{center}\n\n\n\\subsubsection{数学公式}\n\\begin{Code}\n// LeetCode, Gray Code\n// 数学公式，时间复杂度O(2^n)，空间复杂度O(1)\nclass Solution {\npublic:\n    vector<int> grayCode(int n) {\n        vector<int> result;\n        const size_t size = 1 << n;  // 2^n\n        result.reserve(size);\n        for (size_t i = 0; i < size; ++i)\n            result.push_back(binary_to_gray(i));\n        return result;\n    }\nprivate:\n    static unsigned int binary_to_gray(unsigned int n) {\n        return n ^ (n >> 1);\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{Reflect-and-prefix method}\n\\begin{Code}\n// LeetCode, Gray Code\n// reflect-and-prefix method\n// 时间复杂度O(2^n)，空间复杂度O(1)\nclass Solution {\npublic:\n    vector<int> grayCode(int n) {\n        vector<int> result;\n        result.reserve(1<<n);\n        result.push_back(0);\n        for (int i = 0; i < n; i++) {\n            const int highest_bit = 1 << i;\n            for (int j = result.size() - 1; j >= 0; j--) // 要反着遍历，才能对称\n                result.push_back(highest_bit | result[j]);\n        }\n        return result;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item 无\n\\myenddot\n\n\n\\subsection{Set Matrix Zeroes} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:set-matrix-zeroes}\n\n\n\\subsubsection{描述}\nGiven a $m \\times n$ matrix, if an element is 0, set its entire row and column to 0. Do it in place.\n\n\\textbf{Follow up:}\nDid you use extra space?\n\nA straight forward solution using $O(mn)$ space is probably a bad idea.\n\nA simple improvement uses $O(m + n)$ space, but still not the best solution.\n\nCould you devise a constant space solution?\n\n\n\\subsubsection{分析}\n$O(m+n)$空间的方法很简单，设置两个bool数组，记录每行和每列是否存在0。\n\n想要常数空间，可以复用第一行和第一列。\n\n\n\\subsubsection{代码1}\n\\begin{Code}\n// LeetCode, Set Matrix Zeroes\n// 时间复杂度O(m*n)，空间复杂度O(m+n)\nclass Solution {\npublic:\n    void setZeroes(vector<vector<int> > &matrix) {\n        const size_t m = matrix.size();\n        const size_t n = matrix[0].size();\n        vector<bool> row(m, false); // 标记该行是否存在0\n        vector<bool> col(n, false); // 标记该列是否存在0\n\n        for (size_t i = 0; i < m; ++i) {\n            for (size_t j = 0; j < n; ++j) {\n                if (matrix[i][j] == 0) {\n                    row[i] = col[j] = true;\n                }\n            }\n        }\n\n        for (size_t i = 0; i < m; ++i) {\n            if (row[i])\n                fill(&matrix[i][0], &matrix[i][0] + n, 0);\n        }\n        for (size_t j = 0; j < n; ++j) {\n            if (col[j]) {\n                for (size_t i = 0; i < m; ++i) {\n                    matrix[i][j] = 0;\n                }\n            }\n        }\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{代码2}\n\\begin{Code}\n// LeetCode, Set Matrix Zeroes\n// 时间复杂度O(m*n)，空间复杂度O(1)\nclass Solution {\npublic:\n    void setZeroes(vector<vector<int> > &matrix) {\n        const size_t m = matrix.size();\n        const size_t n = matrix[0].size();\n        bool row_has_zero = false; // 第一行是否存在 0\n        bool col_has_zero = false; // 第一列是否存在 0\n\n        for (size_t i = 0; i < n; i++)\n            if (matrix[0][i] == 0) {\n                row_has_zero = true;\n                break;\n            }\n\n        for (size_t i = 0; i < m; i++)\n            if (matrix[i][0] == 0) {\n                col_has_zero = true;\n                break;\n            }\n\n        for (size_t i = 1; i < m; i++)\n            for (size_t j = 1; j < n; j++)\n                if (matrix[i][j] == 0) {\n                    matrix[0][j] = 0;\n                    matrix[i][0] = 0;\n                }\n        for (size_t i = 1; i < m; i++)\n            for (size_t j = 1; j < n; j++)\n                if (matrix[i][0] == 0 || matrix[0][j] == 0)\n                    matrix[i][j] = 0;\n        if (row_has_zero)\n            for (size_t i = 0; i < n; i++)\n                matrix[0][i] = 0;\n        if (col_has_zero)\n            for (size_t i = 0; i < m; i++)\n                matrix[i][0] = 0;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item 无\n\\myenddot\n\n\n\\subsection{Gas Station} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:gas-station}\n\n\n\\subsubsection{描述}\nThere are $N$ gas stations along a circular route, where the amount of gas at station $i$ is \\fn{gas[i]}.\n\nYou have a car with an unlimited gas tank and it costs \\fn{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\nReturn the starting gas station's index if you can travel around the circuit once, otherwise return -1.\n\nNote:\nThe solution is guaranteed to be unique.\n\n\n\\subsubsection{分析}\n首先想到的是$O(N^2)$的解法，对每个点进行模拟。\n\n$O(N)$的解法是，设置两个变量，\\fn{sum}判断当前的指针的有效性；\\fn{total}则判断整个数组是否有解，有就返回通过\\fn{sum}得到的下标，没有则返回-1。\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Gas Station\n// 时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {\n        int total = 0;\n        int j = -1;\n        for (int i = 0, sum = 0; i < gas.size(); ++i) {\n            sum += gas[i] - cost[i];\n            total += gas[i] - cost[i];\n            if (sum < 0) {\n                j = i;\n                sum = 0;\n            }\n        }\n        return total >= 0 ? j + 1 : -1;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item 无\n\\myenddot\n\n\n\\subsection{Candy} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:candy}\n\n\n\\subsubsection{描述}\nThere are $N$ children standing in a line. Each child is assigned a rating value.\n\nYou are giving candies to these children subjected to the following requirements:\n\\begindot\n\\item Each child must have at least one candy.\n\\item Children with a higher rating get more candies than their neighbors.\n\\myenddot\n\nWhat is the minimum candies you must give?\n\n\n\\subsubsection{分析}\n无\n\n\n\\subsubsection{迭代版}\n\\begin{Code}\n// LeetCode, Candy\n// 时间复杂度O(n)，空间复杂度O(n)\nclass Solution {\npublic:\n    int candy(vector<int> &ratings) {\n        const int n = ratings.size();\n        vector<int> increment(n);\n\n        // 左右各扫描一遍\n        for (int i = 1, inc = 1; i < n; i++) {\n            if (ratings[i] > ratings[i - 1])\n                increment[i] = max(inc++, increment[i]);\n            else\n                inc = 1;\n        }\n\n        for (int i = n - 2, inc = 1; i >= 0; i--) {\n            if (ratings[i] > ratings[i + 1])\n                increment[i] = max(inc++, increment[i]);\n            else\n                inc = 1;\n        }\n        // 初始值为n，因为每个小朋友至少一颗糖\n        return accumulate(&increment[0], &increment[0]+n, n);\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{递归版}\n\\begin{Code}\n// LeetCode, Candy\n// 备忘录法，时间复杂度O(n)，空间复杂度O(n)\n// @author fancymouse (http://weibo.com/u/1928162822)\nclass Solution {\npublic:\n    int candy(const vector<int>& ratings) {\n        vector<int> f(ratings.size());\n        int sum = 0;\n        for (int i = 0; i < ratings.size(); ++i)\n            sum += solve(ratings, f, i);\n        return sum;\n    }\n    int solve(const vector<int>& ratings, vector<int>& f, int i) {\n        if (f[i] == 0) {\n            f[i] = 1;\n            if (i > 0 && ratings[i] > ratings[i - 1])\n                f[i] = max(f[i], solve(ratings, f, i - 1) + 1);\n            if (i < ratings.size() - 1 && ratings[i] > ratings[i + 1])\n                f[i] = max(f[i], solve(ratings, f, i + 1) + 1);\n        }\n        return f[i];\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item 无\n\\myenddot\n\n\n\\subsection{Single Number} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:single-number}\n\n\n\\subsubsection{描述}\nGiven an array of integers, every element appears twice except for one. Find that single one.\n\nNote:\nYour algorithm should have a linear runtime complexity. Could you implement it without using extra memory?\n\n\n\\subsubsection{分析}\n异或，不仅能处理两次的情况，只要出现偶数次，都可以清零。\n\n\n\\subsubsection{代码1}\n\\begin{Code}\n// LeetCode, Single Number\n// 时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    int singleNumber(vector<int>& nums) {\n        int x = 0;\n        for (auto i : nums) {\n            x ^= i;\n        }\n        return x;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{代码2}\n\\begin{Code}\n// LeetCode, Single Number\n// 时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    int singleNumber(vector<int>& nums) {\n        return accumulate(nums.begin(), nums.end(), 0, bit_xor<int>());\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item  Single Number II, 见 \\S \\ref{sec:single-number-ii}\n\\myenddot\n\n\n\\subsection{Single Number II} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:single-number-ii}\n\n\n\\subsubsection{描述}\nGiven an array of integers, every element appears three times except for one. Find that single one.\n\nNote:\nYour algorithm should have a linear runtime complexity. Could you implement it without using extra memory?\n\n\n\\subsubsection{分析}\n本题和上一题 Single Number，考察的是位运算。\n\n方法1：创建一个长度为\\fn{sizeof(int)}的数组\\fn{count[sizeof(int)]}，\\fn{count[i]}表示在在$i$位出现的1的次数。如果\\fn{count[i]}是3的整数倍，则忽略；否则就把该位取出来组成答案。\n\n方法2：用\\fn{one}记录到当前处理的元素为止，二进制1出现“1次”（mod 3 之后的 1）的有哪些二进制位；用\\fn{two}记录到当前计算的变量为止，二进制1出现“2次”（mod 3 之后的 2）的有哪些二进制位。当\\fn{one}和\\fn{two}中的某一位同时为1时表示该二进制位上1出现了3次，此时需要清零。即\\textbf{用二进制模拟三进制运算}。最终\\fn{one}记录的是最终结果。\n\n\\subsubsection{代码1}\n\\begin{Code}\n// LeetCode, Single Number II\n// 方法1，时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    int singleNumber(vector<int>& nums) {\n        const int W = sizeof(int) * 8; // 一个整数的bit数，即整数字长\n        int count[W];  // count[i]表示在在i位出现的1的次数\n        fill_n(&count[0], W, 0);\n        for (int i = 0; i < nums.size(); i++) {\n            for (int j = 0; j < W; j++) {\n                count[j] += (nums[i] >> j) & 1;\n                count[j] %= 3;\n            }\n        }\n        int result = 0;\n        for (int i = 0; i < W; i++) {\n            result += (count[i] << i);\n        }\n        return result;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{代码2}\n\\begin{Code}\n// LeetCode, Single Number II\n// 方法2，时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    int singleNumber(vector<int>& nums) {\n        int one = 0, two = 0, three = 0;\n        for (auto i : nums) {\n            two |= (one & i);\n            one ^= i;\n            three = ~(one & two);\n            one &= three;\n            two &= three;\n        }\n\n        return one;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item  Single Number, 见 \\S \\ref{sec:single-number}\n\\myenddot\n\n\n\\section{单链表} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n单链表节点的定义如下：\n\\begin{Code}\n// 单链表节点\nstruct ListNode {\n    int val;\n    ListNode *next;\n    ListNode(int x) : val(x), next(nullptr) { }\n};\n\\end{Code}\n\n\n\\subsection{Add Two Numbers}\n\\label{sec:add-two-numbers}\n\n\n\\subsubsection{描述}\nYou are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.\n\nInput: {\\small \\fontspec{Latin Modern Mono} (2 -> 4 -> 3) + (5 -> 6 -> 4)}\n\nOutput: {\\small \\fontspec{Latin Modern Mono} 7 -> 0 -> 8}\n\n\n\\subsubsection{分析}\n跟Add Binary（见 \\S \\ref{sec:add-binary}）很类似\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Add Two Numbers\n// 跟Add Binary 很类似\n// 时间复杂度O(m+n)，空间复杂度O(1)\nclass Solution {\npublic:\n    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {\n        ListNode dummy(-1); // 头节点\n        int carry = 0;\n        ListNode *prev = &dummy;\n        for (ListNode *pa = l1, *pb = l2;\n             pa != nullptr || pb != nullptr;\n             pa = pa == nullptr ? nullptr : pa->next,\n             pb = pb == nullptr ? nullptr : pb->next,\n             prev = prev->next) {\n            const int ai = pa == nullptr ? 0 : pa->val;\n            const int bi = pb == nullptr ? 0 : pb->val;\n            const int value = (ai + bi + carry) % 10;\n            carry = (ai + bi + carry) / 10;\n            prev->next = new ListNode(value); // 尾插法\n        }\n        if (carry > 0)\n            prev->next = new ListNode(carry);\n        return dummy.next;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\n\\begindot\n\\item Add Binary, 见 \\S \\ref{sec:add-binary}\n\\myenddot\n\n\n\\subsection{Reverse Linked List II}\n\\label{sec:reverse-linked-list-ii}\n\n\n\\subsubsection{描述}\nReverse a linked list from position $m$ to $n$. Do it in-place and in one-pass.\n\nFor example:\nGiven \\code{1->2->3->4->5->nullptr}, $m$ = 2 and $n$ = 4,\n\nreturn \\code{1->4->3->2->5->nullptr}.\n\nNote:\nGiven m, n satisfy the following condition:\n$1 \\leq m \\leq  n \\leq $ length of list.\n\n\n\\subsubsection{分析}\n这题非常繁琐，有很多边界检查，15分钟内做到bug free很有难度！\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Reverse Linked List II\n// 迭代版，时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    ListNode *reverseBetween(ListNode *head, int m, int n) {\n        ListNode dummy(-1);\n        dummy.next = head;\n\n        ListNode *prev = &dummy;\n        for (int i = 0; i < m-1; ++i)\n            prev = prev->next;\n        ListNode* const head2 = prev;\n\n        prev = head2->next;\n        ListNode *cur = prev->next;\n        for (int i = m; i < n; ++i) {\n            prev->next = cur->next;\n            cur->next = head2->next;\n            head2->next = cur;  // 头插法\n            cur = prev->next;\n        }\n\n        return dummy.next;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\n\\begindot\n\\item 无\n\\myenddot\n\n\n\\subsection{Partition List}\n\\label{sec:partition-list}\n\n\n\\subsubsection{描述}\nGiven 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\nYou should preserve the original relative order of the nodes in each of the two partitions.\n\nFor example,\nGiven \\code{1->4->3->2->5->2} and \\code{x = 3}, return \\code{1->2->2->4->3->5}.\n\n\n\\subsubsection{分析}\n无\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Partition List\n// 时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    ListNode* partition(ListNode* head, int x) {\n        ListNode left_dummy(-1); // 头结点\n        ListNode right_dummy(-1); // 头结点\n\n        auto left_cur = &left_dummy;\n        auto right_cur = &right_dummy;\n\n        for (ListNode *cur = head; cur; cur = cur->next) {\n            if (cur->val < x) {\n                left_cur->next = cur;\n                left_cur = cur;\n            } else {\n                right_cur->next = cur;\n                right_cur = cur;\n            }\n        }\n\n        left_cur->next = right_dummy.next;\n        right_cur->next = nullptr;\n\n        return left_dummy.next;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\n\\begindot\n\\item 无\n\\myenddot\n\n\n\\subsection{Remove Duplicates from Sorted List}\n\\label{sec:remove-duplicates-from-sorted-list}\n\n\n\\subsubsection{描述}\nGiven a sorted linked list, delete all duplicates such that each element appear only once.\n\nFor example,\n\nGiven \\code{1->1->2}, return \\code{1->2}.\n\nGiven \\code{1->1->2->3->3}, return \\code{1->2->3}.\n\n\n\\subsubsection{分析}\n无\n\n\n\\subsubsection{递归版}\n\\begin{Code}\n// LeetCode, Remove Duplicates from Sorted List\n// 递归版，时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    ListNode *deleteDuplicates(ListNode *head) {\n        if (!head) return head;\n        ListNode dummy(head->val + 1); // 值只要跟head不同即可\n        dummy.next = head;\n\n        recur(&dummy, head);\n        return dummy.next;\n    }\nprivate:\n    static void recur(ListNode *prev, ListNode *cur) {\n        if (cur == nullptr) return;\n\n        if (prev->val == cur->val) { // 删除head\n            prev->next = cur->next;\n            delete cur;\n            recur(prev, prev->next);\n        } else {\n            recur(prev->next, cur->next);\n        }\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{迭代版}\n\\begin{Code}\n// LeetCode, Remove Duplicates from Sorted List\n// 迭代版，时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    ListNode *deleteDuplicates(ListNode *head) {\n        if (head == nullptr) return nullptr;\n\n        for (ListNode *prev = head, *cur = head->next; cur; cur = prev->next) {\n            if (prev->val == cur->val) {\n                prev->next = cur->next;\n                delete cur;\n            } else {\n                prev = cur;\n            }\n        }\n        return head;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\n\\begindot\n\\item Remove Duplicates from Sorted List II，见 \\S \\ref{sec:remove-duplicates-from-sorted-list-ii}\n\\myenddot\n\n\n\\subsection{Remove Duplicates from Sorted List II}\n\\label{sec:remove-duplicates-from-sorted-list-ii}\n\n\n\\subsubsection{描述}\nGiven a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.\n\nFor example,\n\nGiven \\code{1->2->3->3->4->4->5}, return \\code{1->2->5}.\n\nGiven \\code{1->1->1->2->3}, return \\code{2->3}.\n\n\n\\subsubsection{分析}\n无\n\n\n\\subsubsection{递归版}\n\\begin{Code}\n// LeetCode, Remove Duplicates from Sorted List II\n// 递归版，时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    ListNode *deleteDuplicates(ListNode *head) {\n        if (!head || !head->next) return head;\n\n        ListNode *p = head->next;\n        if (head->val == p->val) {\n            while (p && head->val == p->val) {\n                ListNode *tmp = p;\n                p = p->next;\n                delete tmp;\n            }\n            delete head;\n            return deleteDuplicates(p);\n        } else {\n            head->next = deleteDuplicates(head->next);\n            return head;\n        }\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{迭代版}\n\\begin{Code}\n// LeetCode, Remove Duplicates from Sorted List II\n// 迭代版，时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    ListNode *deleteDuplicates(ListNode *head) {\n        if (head == nullptr) return head;\n\n        ListNode dummy(INT_MIN); // 头结点\n        dummy.next = head;\n        ListNode *prev = &dummy, *cur = head;\n        while (cur != nullptr) {\n            bool duplicated = false;\n            while (cur->next != nullptr && cur->val == cur->next->val) {\n                duplicated = true;\n                ListNode *temp = cur;\n                cur = cur->next;\n                delete temp;\n            }\n            if (duplicated) { // 删除重复的最后一个元素\n                ListNode *temp = cur;\n                cur = cur->next;\n                delete temp;\n                continue;\n            }\n            prev->next = cur;\n            prev = prev->next;\n            cur = cur->next;\n        }\n        prev->next = cur;\n        return dummy.next;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\n\\begindot\n\\item Remove Duplicates from Sorted List，见 \\S \\ref{sec:remove-duplicates-from-sorted-list}\n\\myenddot\n\n\n\\subsection{Rotate List}\n\\label{sec:rotate-list}\n\n\n\\subsubsection{描述}\nGiven a list, rotate the list to the right by $k$ places, where $k$ is non-negative.\n\nFor example:\nGiven \\code{1->2->3->4->5->nullptr} and \\code{k = 2}, return \\code{4->5->1->2->3->nullptr}.\n\n\n\\subsubsection{分析}\n先遍历一遍，得出链表长度$len$，注意$k$可能大于$len$，因此令$k \\%= len$。将尾节点next指针指向首节点，形成一个环，接着往后跑$len-k$步，从这里断开，就是要求的结果了。\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Remove Rotate List\n// 时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    ListNode *rotateRight(ListNode *head, int k) {\n        if (head == nullptr || k == 0) return head;\n\n        int len = 1;\n        ListNode* p = head;\n        while (p->next) { // 求长度\n            len++;\n            p = p->next;\n        }\n        k = len - k % len;\n\n        p->next = head; // 首尾相连\n        for(int step = 0; step < k; step++) {\n            p = p->next;  //接着往后跑\n        }\n        head = p->next; // 新的首节点\n        p->next = nullptr; // 断开环\n        return head;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\n\\begindot\n\\item 无\n\\myenddot\n\n\n\\subsection{Remove Nth Node From End of List}\n\\label{sec:remove-nth-node-from-end-of-list}\n\n\n\\subsubsection{描述}\nGiven a linked list, remove the $n^{th}$ node from the end of list and return its head.\n\nFor example, Given linked list: \\code{1->2->3->4->5}, and $n$ = 2.\n\nAfter removing the second node from the end, the linked list becomes \\code{1->2->3->5}.\n\nNote:\n\\begindot\n\\item Given $n$ will always be valid.\n\\item Try to do this in one pass.\n\\myenddot\n\n\n\\subsubsection{分析}\n设两个指针$p,q$，让$q$先走$n$步，然后$p$和$q$一起走，直到$q$走到尾节点，删除\\fn{p->next}即可。\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Remove Nth Node From End of List\n// 时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    ListNode *removeNthFromEnd(ListNode *head, int n) {\n        ListNode dummy{-1, head};\n        ListNode *p = &dummy, *q = &dummy;\n\n        for (int i = 0; i < n; i++)  // q先走n步\n            q = q->next;\n\n        while(q->next) { // 一起走\n            p = p->next;\n            q = q->next;\n        }\n        ListNode *tmp = p->next;\n        p->next = p->next->next;\n        delete tmp;\n        return dummy.next;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\n\\begindot\n\\item 无\n\\myenddot\n\n\n\\subsection{Swap Nodes in Pairs}\n\\label{sec:swap-nodes-in-pairs}\n\n\n\\subsubsection{描述}\nGiven a linked list, swap every two adjacent nodes and return its head.\n\nFor example,\nGiven \\code{1->2->3->4}, you should return the list as \\code{2->1->4->3}.\n\nYour algorithm should use only constant space. You may \\emph{not} modify the values in the list, only nodes itself can be changed.\n\n\n\\subsubsection{分析}\n无\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Swap Nodes in Pairs\n// 时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    ListNode *swapPairs(ListNode *head) {\n        if (head == nullptr || head->next == nullptr) return head;\n        ListNode dummy(-1);\n        dummy.next = head;\n\n        for(ListNode *prev = &dummy, *cur = prev->next, *next = cur->next;\n                next;\n                prev = cur, cur = cur->next, next = cur ? cur->next: nullptr) {\n            prev->next = next;\n            cur->next = next->next;\n            next->next = cur;\n        }\n        return dummy.next;\n    }\n};\n\\end{Code}\n\n下面这种写法更简洁，但题目规定了不准这样做。\n\\begin{Code}\n// LeetCode, Swap Nodes in Pairs\n// 时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    ListNode* swapPairs(ListNode* head) {\n        ListNode* p = head;\n\n        while (p && p->next) {\n            swap(p->val, p->next->val);\n            p = p->next->next;\n        }\n\n        return head;\n    }\n};\n\\end{Code}\n\n\\subsubsection{相关题目}\n\n\\begindot\n\\item Reverse Nodes in k-Group, 见 \\S \\ref{sec:reverse-nodes-in-k-group}\n\\myenddot\n\n\n\\subsection{Reverse Nodes in k-Group}\n\\label{sec:reverse-nodes-in-k-group}\n\n\n\\subsubsection{描述}\nGiven a linked list, reverse the nodes of a linked list k at a time and return its modified list.\n\nIf the number of nodes is not a multiple of $k$ then left-out nodes in the end should remain as it is.\n\nYou may not alter the values in the nodes, only nodes itself may be changed.\n\nOnly constant memory is allowed.\n\nFor example,\nGiven this linked list: \\code{1->2->3->4->5}\n\nFor $k = 2$, you should return: \\code{2->1->4->3->5}\n\nFor $k = 3$, you should return: \\code{3->2->1->4->5}\n\n\n\\subsubsection{分析}\n无\n\n\n\\subsubsection{递归版}\n\\begin{Code}\n// LeetCode, Reverse Nodes in k-Group\n// 递归版，时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    ListNode *reverseKGroup(ListNode *head, int k) {\n        if (head == nullptr || head->next == nullptr || k < 2)\n            return head;\n\n        ListNode *next_group = head;\n        for (int i = 0; i < k; ++i) {\n            if (next_group)\n                next_group = next_group->next;\n            else\n                return head;\n        }\n        // next_group is the head of next group\n        // new_next_group is the new head of next group after reversion\n        ListNode *new_next_group = reverseKGroup(next_group, k);\n        ListNode *prev = NULL, *cur = head;\n        while (cur != next_group) {\n            ListNode *next = cur->next;\n            cur->next = prev ? prev : new_next_group;\n            prev = cur;\n            cur = next;\n        }\n        return prev; // prev will be the new head of this group\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{迭代版}\n\\begin{Code}\n// LeetCode, Reverse Nodes in k-Group\n// 迭代版，时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    ListNode *reverseKGroup(ListNode *head, int k) {\n        if (head == nullptr || head->next == nullptr || k < 2) return head;\n        ListNode dummy(-1);\n        dummy.next = head;\n\n        for(ListNode *prev = &dummy, *end = head; end; end = prev->next) {\n            for (int i = 1; i < k && end; i++)\n                end = end->next;\n            if (end  == nullptr) break;  // 不足 k 个\n\n            prev = reverse(prev, prev->next, end);\n        }\n\n        return dummy.next;\n    }\n\n    // prev 是 first 前一个元素, [begin, end] 闭区间，保证三者都不为 null\n    // 返回反转后的倒数第1个元素\n    ListNode* reverse(ListNode *prev, ListNode *begin, ListNode *end) {\n        ListNode *end_next = end->next;\n        for (ListNode *p = begin, *cur = p->next, *next = cur->next;\n                cur != end_next;\n                p = cur, cur = next, next = next ? next->next : nullptr) {\n            cur->next = p;\n        }\n        begin->next = end_next;\n        prev->next = end;\n        return begin;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Swap Nodes in Pairs, 见 \\S \\ref{sec:swap-nodes-in-pairs}\n\\myenddot\n\n\n\\subsection{Copy List with Random Pointer}\n\\label{sec:copy-list-with-random-pointer}\n\n\n\\subsubsection{描述}\nA linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.\n\nReturn a deep copy of the list.\n\n\n\\subsubsection{分析}\n无\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Copy List with Random Pointer\n// 两遍扫描，时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    RandomListNode *copyRandomList(RandomListNode *head) {\n        for (RandomListNode* cur = head; cur != nullptr; ) {\n            RandomListNode* node = new RandomListNode(cur->label);\n            node->next = cur->next;\n            cur->next = node;\n            cur = node->next;\n        }\n\n        for (RandomListNode* cur = head; cur != nullptr; ) {\n            if (cur->random != NULL)\n                cur->next->random = cur->random->next;\n            cur = cur->next->next;\n        }\n\n        // 分拆两个单链表\n        RandomListNode dummy(-1);\n        for (RandomListNode* cur = head, *new_cur = &dummy;\n                cur != nullptr; ) {\n            new_cur->next = cur->next;\n            new_cur = new_cur->next;\n            cur->next = cur->next->next;\n            cur = cur->next;\n        }\n        return dummy.next;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item 无\n\\myenddot\n\n\n\\subsection{Linked List Cycle}\n\\label{sec:linked-list-cycle}\n\n\n\\subsubsection{描述}\nGiven a linked list, determine if it has a cycle in it.\n\nFollow up:\nCan you solve it without using extra space?\n\n\n\\subsubsection{分析}\n最容易想到的方法是，用一个哈希表\\fn{unordered_map<int, bool> visited}，记录每个元素是否被访问过，一旦出现某个元素被重复访问，说明存在环。空间复杂度$O(n)$，时间复杂度$O(N)$。\n\n最好的方法是时间复杂度$O(n)$，空间复杂度$O(1)$的。设置两个指针，一个快一个慢，快的指针每次走两步，慢的指针每次走一步，如果快指针和慢指针相遇，则说明有环。参考\\myurl{ http://leetcode.com/2010/09/detecting-loop-in-singly-linked-list.html}\n\n\n\\subsubsection{代码}\n\\begin{Code}\n//LeetCode, Linked List Cycle\n// 时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    bool hasCycle(ListNode *head) {\n        // 设置两个指针，一个快一个慢\n        ListNode *slow = head, *fast = head;\n        while (fast && fast->next) {\n            slow = slow->next;\n            fast = fast->next->next;\n            if (slow == fast) return true;\n        }\n        return false;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Linked List Cycle II, 见 \\S \\ref{sec:Linked-List-Cycle-II}\n\\myenddot\n\n\n\\subsection{Linked List Cycle II}\n\\label{sec:linked-list-cycle-ii}\n\n\n\\subsubsection{描述}\nGiven a linked list, return the node where the cycle begins. If there is no cycle, return \\fn{null}.\n\nFollow up:\nCan you solve it without using extra space?\n\n\n\\subsubsection{分析}\n当fast与slow相遇时，slow肯定没有遍历完链表，而fast已经在环内循环了$n$圈($1 \\leq n$)。假设slow走了$s$步，则fast走了$2s$步（fast步数还等于$s$加上在环上多转的$n$圈），设环长为$r$，则：\n\\begin{eqnarray}\n2s &=& s + nr \\nonumber \\\\\ns &=& nr \\nonumber\n\\end{eqnarray}\n\n设整个链表长$L$，环入口点与相遇点距离为$a$，起点到环入口点的距离为$x$，则\n\\begin{eqnarray}\nx + a &=& nr = (n – 1)r +r = (n-1)r + L - x \\nonumber \\\\\nx &=& (n-1)r + (L – x – a) \\nonumber\n\\end{eqnarray}\n\n$L – x – a$为相遇点到环入口点的距离，由此可知，从链表头到环入口点等于$n-1$圈内环+相遇点到环入口点，于是我们可以从\\fn{head}开始另设一个指针\\fn{slow2}，两个慢指针每次前进一步，它俩一定会在环入口点相遇。\n\n\n\\subsubsection{代码}\n\\begin{Code}\n//LeetCode, Linked List Cycle II\n// 时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    ListNode *detectCycle(ListNode *head) {\n        ListNode *slow = head, *fast = head;\n        while (fast && fast->next) {\n            slow = slow->next;\n            fast = fast->next->next;\n            if (slow == fast) {\n                ListNode *slow2 = head;\n\n                while (slow2 != slow) {\n                    slow2 = slow2->next;\n                    slow = slow->next;\n                }\n                return slow2;\n            }\n        }\n        return nullptr;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Linked List Cycle, 见 \\S \\ref{sec:Linked-List-Cycle}\n\\myenddot\n\n\n\\subsection{Reorder List}\n\\label{sec:reorder-list}\n\n\n\\subsubsection{描述}\nGiven a singly linked list $L: L_0 \\rightarrow L_1 \\rightarrow \\cdots \\rightarrow L_{n-1} \\rightarrow L_n$,\nreorder it to: $L_0 \\rightarrow L_n \\rightarrow L_1 \\rightarrow L_{n-1} \\rightarrow L_2 \\rightarrow L_{n-2} \\rightarrow \\cdots$\n\nYou must do this in-place without altering the nodes' values.\n\nFor example,\nGiven \\fn{\\{1,2,3,4\\}}, reorder it to \\fn{\\{1,4,2,3\\}}.\n\n\n\\subsubsection{分析}\n题目规定要in-place，也就是说只能使用$O(1)$的空间。\n\n可以找到中间节点，断开，把后半截单链表reverse一下，再合并两个单链表。\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Reorder List\n// 时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    void reorderList(ListNode *head) {\n        if (head == nullptr || head->next == nullptr) return;\n\n        ListNode *slow = head, *fast = head, *prev = nullptr;\n        while (fast && fast->next) {\n            prev = slow;\n            slow = slow->next;\n            fast = fast->next->next;\n        }\n        prev->next = nullptr; // cut at middle\n\n        slow = reverse(slow);\n\n        // merge two lists\n        ListNode *curr = head;\n        while (curr->next) {\n            ListNode *tmp = curr->next;\n            curr->next = slow;\n            slow = slow->next;\n            curr->next->next = tmp;\n            curr = tmp;\n        }\n        curr->next = slow;\n    }\n\n    ListNode* reverse(ListNode *head) {\n        if (head == nullptr || head->next == nullptr) return head;\n\n        ListNode *prev = head;\n        for (ListNode *curr = head->next, *next = curr->next; curr;\n            prev = curr, curr = next, next = next ? next->next : nullptr) {\n                curr->next = prev;\n        }\n        head->next = nullptr;\n        return prev;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item 无\n\\myenddot\n\n\n\\subsection{LRU Cache}\n\\label{sec:lru-cache}\n\n\n\\subsubsection{描述}\nDesign and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.\n\n\\fn{get(key)} - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.\n\n\\fn{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\n\\subsubsection{分析}\n为了使查找、插入和删除都有较高的性能，我们使用一个双向链表(\\fn{std::list})和一个哈希表(\\fn{std::unordered_map})，因为：\n\\begin{itemize}\n\\item{哈希表保存每个节点的地址，可以基本保证在$O(1)$时间内查找节点}\n\\item{双向链表插入和删除效率高，单向链表插入和删除时，还要查找节点的前驱节点}\n\\end{itemize}\n\n具体实现细节：\n\\begin{itemize}\n\\item{越靠近链表头部，表示节点上次访问距离现在时间最短，尾部的节点表示最近访问最少}\n\\item{访问节点时，如果节点存在，把该节点交换到链表头部，同时更新hash表中该节点的地址}\n\\item{插入节点时，如果cache的size达到了上限capacity，则删除尾部节点，同时要在hash表中删除对应的项；新节点插入链表头部}              \n\\end{itemize}\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, LRU Cache\n// 时间复杂度O(logn)，空间复杂度O(n)\nclass LRUCache{\nprivate:\n    struct CacheNode {\n        int key;\n        int value;\n        CacheNode(int k, int v) :key(k), value(v){}\n    };\npublic:\n    LRUCache(int capacity) {\n        this->capacity = capacity;\n    }\n\n    int get(int key) {\n        if (cacheMap.find(key) == cacheMap.end()) return -1;\n        \n        // 把当前访问的节点移到链表头部，并且更新map中该节点的地址\n        cacheList.splice(cacheList.begin(), cacheList, cacheMap[key]); \n        cacheMap[key] = cacheList.begin();\n        return cacheMap[key]->value;\n    }\n\n    void set(int key, int value) {\n        if (cacheMap.find(key) == cacheMap.end()) {\n            if (cacheList.size() == capacity) { //删除链表尾部节点（最少访问的节点）\n                cacheMap.erase(cacheList.back().key);\n                cacheList.pop_back();\n            }\n            // 插入新节点到链表头部, 并且在map中增加该节点\n            cacheList.push_front(CacheNode(key, value));\n            cacheMap[key] = cacheList.begin();\n        } else {\n            //更新节点的值，把当前访问的节点移到链表头部,并且更新map中该节点的地址\n            cacheMap[key]->value = value;\n            cacheList.splice(cacheList.begin(), cacheList, cacheMap[key]);\n            cacheMap[key] = cacheList.begin();\n        }\n    }\nprivate:\n    list<CacheNode> cacheList;\n    unordered_map<int, list<CacheNode>::iterator> cacheMap;\n    int capacity;\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item 无\n\\myenddot\n\n"
  },
  {
    "path": "C++/chapSearching.tex",
    "content": "\\chapter{查找}\n\n\n\\section{Search for a Range} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:search-for-a-range}\n\n\n\\subsubsection{描述}\nGiven a sorted array of integers, find the starting and ending position of a given target value.\n\nYour algorithm's runtime complexity must be in the order of $O(\\log n)$.\n\nIf the target is not found in the array, return \\code{[-1, -1]}.\n\nFor example,\nGiven \\code{[5, 7, 7, 8, 8, 10]} and target value 8,\nreturn \\code{[3, 4]}.\n\n\n\\subsubsection{分析}\n已经排好了序，用二分查找。\n\n\n\\subsubsection{使用STL}\n\\begin{Code}\n// LeetCode, Search for a Range\n// 偷懒的做法，使用STL\n// 时间复杂度O(logn)，空间复杂度O(1)\nclass Solution {\npublic:\n    vector<int> searchRange(vector<int>& nums, int target) {\n        const int l = distance(nums.begin(), lower_bound(nums.begin(), nums.end(), target));\n        const int u = distance(nums.begin(), prev(upper_bound(nums.begin(), nums.end(), target)));\n        if (nums[l] != target) // not found\n            return vector<int> { -1, -1 };\n        else\n            return vector<int> { l, u };\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{重新实现 lower_bound 和 upper_bound}\n\\begin{Code}\n// LeetCode, Search for a Range\n// 重新实现 lower_bound 和 upper_bound\n// 时间复杂度O(logn)，空间复杂度O(1)\nclass Solution {\npublic:\n    vector<int> searchRange (vector<int>& nums, int target) {\n        auto lower = lower_bound(nums.begin(), nums.end(), target);\n        auto uppper = upper_bound(lower, nums.end(), target);\n\n        if (lower == nums.end() || *lower != target)\n            return vector<int> { -1, -1 };\n        else\n            return vector<int> {distance(nums.begin(), lower), distance(nums.begin(), prev(uppper))};\n    }\n\n    template<typename ForwardIterator, typename T>\n    ForwardIterator lower_bound (ForwardIterator first,\n            ForwardIterator last, T value) {\n        while (first != last) {\n            auto mid = next(first, distance(first, last) / 2);\n\n            if (value > *mid)   first = ++mid;\n            else                last = mid;\n        }\n\n        return first;\n    }\n\n    template<typename ForwardIterator, typename T>\n    ForwardIterator upper_bound (ForwardIterator first,\n            ForwardIterator last, T value) {\n        while (first != last) {\n            auto mid = next(first, distance (first, last) / 2);\n\n            if (value >= *mid)   first = ++mid;  // 与 lower_bound 仅此不同\n            else                 last = mid;\n        }\n\n        return first;\n    }\n};\n\\end{Code}\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Search Insert Position, 见 \\S \\ref{sec:search-insert-position}\n\\myenddot\n\n\n\\section{Search Insert Position} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:search-insert-position}\n\n\n\\subsubsection{描述}\nGiven 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\nYou may assume no duplicates in the array.\n\nHere are few examples.\n\\begin{Code}\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\\end{Code}\n\n\n\\subsubsection{分析}\n即\\fn{std::lower_bound()}。\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Search Insert Position\n// 重新实现 lower_bound\n// 时间复杂度O(logn)，空间复杂度O(1)\nclass Solution {\npublic:\n    int searchInsert(vector<int>& nums, int target) {\n        return distance(nums.begin(), lower_bound(nums.begin(), nums.end(), target));\n    }\n\n    template<typename ForwardIterator, typename T>\n    ForwardIterator lower_bound (ForwardIterator first,\n            ForwardIterator last, T value) {\n        while (first != last) {\n            auto mid = next(first, distance(first, last) / 2);\n\n            if (value > *mid)   first = ++mid;\n            else                last = mid;\n        }\n\n        return first;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Search for a Range, 见 \\S \\ref{sec:search-for-a-range}\n\\myenddot\n\n\n\\section{Search a 2D Matrix} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:search-a-2d-matrix}\n\n\n\\subsubsection{描述}\nWrite an efficient algorithm that searches for a value in an $m \\times n$ matrix. This matrix has the following properties:\n\\begindot\n\\item Integers in each row are sorted from left to right.\n\\item The first integer of each row is greater than the last integer of the previous row.\n\\myenddot\n\nFor example, Consider the following matrix:\n\\begin{Code}\n[\n  [1,   3,  5,  7],\n  [10, 11, 16, 20],\n  [23, 30, 34, 50]\n]\n\\end{Code}\nGiven \\fn{target = 3}, return true.\n\n\n\\subsubsection{分析}\n二分查找。\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Search a 2D Matrix\n// 时间复杂度O(logn)，空间复杂度O(1)\nclass Solution {\npublic:\n    bool searchMatrix(const vector<vector<int>>& matrix, int target) {\n        if (matrix.empty()) return false;\n        const size_t  m = matrix.size();\n        const size_t n = matrix.front().size();\n\n        int first = 0;\n        int last = m * n;\n\n        while (first < last) {\n            int mid = first + (last - first) / 2;\n            int value = matrix[mid / n][mid % n];\n\n            if (value == target)\n                return true;\n            else if (value < target)\n                first = mid + 1;\n            else\n                last = mid;\n        }\n\n        return false;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item 无\n\\myenddot\n"
  },
  {
    "path": "C++/chapSorting.tex",
    "content": "\\chapter{排序}\n\n\\section{Merge Two Sorted Arrays} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:merge-two-sorted-arrays}\n\n\n\\subsubsection{描述}\nGiven two sorted integer arrays A and B, merge B into A as one sorted array.\n\nNote:\nYou may assume that A has enough space to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.\n\n\n\\subsubsection{分析}\n无\n\n\n\\subsubsection{代码}\n\\begin{Code}\n//LeetCode, Merge Sorted Array\n// 时间复杂度O(m+n)，空间复杂度O(1)\nclass Solution {\npublic:\n    void merge(vector<int>& A, int m, vector<int>& B, int n) {\n        int ia = m - 1, ib = n - 1, icur = m + n - 1;\n        while(ia >= 0 && ib >= 0) {\n            A[icur--] = A[ia] >= B[ib] ? A[ia--] : B[ib--];\n        }\n        while(ib >= 0) {\n            A[icur--] = B[ib--];\n        }\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Merge Two Sorted Lists，见 \\S \\ref{sec:merge-two-sorted-lists}\n\\item Merge k Sorted Lists，见 \\S \\ref{sec:merge-k-sorted-lists}\n\\myenddot\n\n\n\\section{Merge Two Sorted Lists} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:merge-two-sorted-lists}\n\n\n\\subsubsection{描述}\nMerge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.\n\n\n\\subsubsection{分析}\n无\n\n\n\\subsubsection{代码}\n\\begin{Code}\n//LeetCode, Merge Two Sorted Lists\n// 时间复杂度O(min(m,n))，空间复杂度O(1)\nclass Solution {\npublic:\n    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {\n        if (l1 == nullptr) return l2;\n        if (l2 == nullptr) return l1;\n        ListNode dummy(-1);\n        ListNode *p = &dummy;\n        for (; l1 != nullptr && l2 != nullptr; p = p->next) {\n            if (l1->val > l2->val) { p->next = l2; l2 = l2->next; }\n            else { p->next = l1; l1 = l1->next; }\n        }\n        p->next = l1 != nullptr ? l1 : l2;\n        return dummy.next;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Merge Sorted Array \\S \\ref{sec:merge-sorted-array}\n\\item Merge k Sorted Lists，见 \\S \\ref{sec:merge-k-sorted-lists}\n\\myenddot\n\n\n\\section{Merge k Sorted Lists} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:merge-k-sorted-lists}\n\n\n\\subsubsection{描述}\nMerge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.\n\n\n\\subsubsection{分析}\n可以复用Merge Two Sorted Lists（见 \\S \\ref{sec:merge-two-sorted-lists}）的函数\n\n\n\\subsubsection{代码}\n\\begin{Code}\n//LeetCode, Merge k Sorted Lists\n// 时间复杂度O(n1+n2+...)，空间复杂度O(1)\nclass Solution {\npublic:\n\n    ListNode * mergeTwo(ListNode * l1, ListNode * l2){\n        if(!l1) return l2;\n        if(!l2) return l1;\n        ListNode dummy(-1);\n        ListNode * p = &dummy;\n        for(; l1 && l2; p = p->next){\n            if(l1->val > l2->val){\n                p->next = l2; l2 = l2->next;\n            }\n            else{\n                p->next = l1; l1 = l1->next;\n            }\n        }\n        p->next = l1 ? l1 : l2;\n        return dummy.next;\n    }\n\n    ListNode* mergeKLists(vector<ListNode*>& lists) {\n        if(lists.size() == 0) return nullptr;\n\n        // multi pass\n        deque<ListNode *> dq(lists.begin(), lists.end());\n        while(dq.size() > 1){\n            ListNode * first = dq.front(); dq.pop_front();\n            ListNode * second = dq.front(); dq.pop_front();\n            dq.push_back(mergeTwo(first,second));\n        }\n\n        return dq.front();\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Merge Sorted Array \\S \\ref{sec:merge-sorted-array}\n\\item Merge Two Sorted Lists，见 \\S \\ref{sec:merge-two-sorted-lists}\n\\myenddot\n\n\n\\section{Insertion Sort List} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:insertion-sort-list}\n\n\n\\subsubsection{描述}\nSort a linked list using insertion sort.\n\n\n\\subsubsection{分析}\n无\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Insertion Sort List\n// 时间复杂度O(n^2)，空间复杂度O(1)\nclass Solution {\npublic:\n    ListNode *insertionSortList(ListNode *head) {\n        ListNode dummy(INT_MIN);\n        //dummy.next = head;\n\n        for (ListNode *cur = head; cur != nullptr;) {\n            auto pos = findInsertPos(&dummy, cur->val);\n            ListNode *tmp = cur->next;\n            cur->next = pos->next;\n            pos->next = cur;\n            cur = tmp;\n        }\n        return dummy.next;\n    }\n\n    ListNode* findInsertPos(ListNode *head, int x) {\n        ListNode *pre = nullptr;\n        for (ListNode *cur = head; cur != nullptr && cur->val <= x;\n            pre = cur, cur = cur->next)\n            ;\n        return pre;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Sort List, 见 \\S \\ref{sec:Sort-List}\n\\myenddot\n\n\n\\section{Sort List} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:sort-list}\n\n\n\\subsubsection{描述}\nSort a linked list in $O(n log n)$ time using constant space complexity.\n\n\n\\subsubsection{分析}\n常数空间且$O(nlogn)$，单链表适合用归并排序，双向链表适合用快速排序。本题可以复用 \"Merge Two Sorted Lists\" 的代码。\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Sort List\n// 归并排序，时间复杂度O(nlogn)，空间复杂度O(1)\nclass Solution {\npublic:\n    ListNode *sortList(ListNode *head) {\n        if (head == NULL || head->next == NULL)return head;\n\n        // 快慢指针找到中间节点\n        ListNode *fast = head, *slow = head;\n        while (fast->next != NULL && fast->next->next != NULL) {\n            fast = fast->next->next;\n            slow = slow->next;\n        }\n        // 断开\n        fast = slow;\n        slow = slow->next;\n        fast->next = NULL;\n\n        ListNode *l1 = sortList(head);  // 前半段排序\n        ListNode *l2 = sortList(slow);  // 后半段排序\n        return mergeTwoLists(l1, l2);\n    }\n\n    // Merge Two Sorted Lists\n    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {\n        ListNode dummy(-1);\n        for (ListNode* p = &dummy; l1 != nullptr || l2 != nullptr; p = p->next) {\n            int val1 = l1 == nullptr ? INT_MAX : l1->val;\n            int val2 = l2 == nullptr ? INT_MAX : l2->val;\n            if (val1 <= val2) {\n                p->next = l1;\n                l1 = l1->next;\n            } else {\n                p->next = l2;\n                l2 = l2->next;\n            }\n        }\n        return dummy.next;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Insertion Sort List，见 \\S \\ref{sec:Insertion-Sort-List}\n\\myenddot\n\n\n\\section{First Missing Positive} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:first-missing-positive}\n\n\n\\subsubsection{描述}\nGiven an unsorted integer array, find the first missing positive integer.\n\nFor example,\nGiven \\fn{[1,2,0]} return \\fn{3},\nand \\fn{[3,4,-1,1]} return \\fn{2}.\n\nYour algorithm should run in $O(n)$ time and uses constant space.\n\n\n\\subsubsection{分析}\n本质上是桶排序(bucket sort)，每当\\fn{A[i]!= i+1}的时候，将A[i]与A[A[i]-1]交换，直到无法交换为止，终止条件是 \\fn{A[i]== A[A[i]-1]}。\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, First Missing Positive\n// 时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    int firstMissingPositive(vector<int>& nums) {\n        bucket_sort(nums);\n\n        for (int i = 0; i < nums.size(); ++i)\n            if (nums[i] != (i + 1))\n                return i + 1;\n        return nums.size() + 1;\n    }\nprivate:\n    static void bucket_sort(vector<int>& A) {\n        const int n = A.size();\n        for (int i = 0; i < n; i++) {\n            while (A[i] != i + 1) {\n                if (A[i] <= 0 || A[i] > n || A[i] == A[A[i] - 1])\n                    break;\n                swap(A[i], A[A[i] - 1]);\n            }\n        }\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Sort Colors, 见 \\S \\ref{sec:sort-colors}\n\\myenddot\n\n\n\\section{Sort Colors} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:sort-colors}\n\n\n\\subsubsection{描述}\nGiven an array with $n$ objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.\n\nHere, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.\n\nNote:\nYou are not suppose to use the library's sort function for this problem.\n\n\\textbf{Follow up:}\n\nA rather straight forward solution is a two-pass algorithm using counting sort.\n\nFirst, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.\n\nCould you come up with an one-pass algorithm using only constant space?\n\n\n\\subsubsection{分析}\n由于0, 1, 2 非常紧凑，首先想到计数排序(counting sort)，但需要扫描两遍，不符合题目要求。\n\n由于只有三种颜色，可以设置两个index，一个是red的index，一个是blue的index，两边往中间走。时间复杂度$O(n)$，空间复杂度$O(1)$。\n\n第3种思路，利用快速排序里 partition 的思想，第一次将数组按0分割，第二次按1分割，排序完毕，可以推广到$n$种颜色，每种颜色有重复元素的情况。\n\n\n\\subsubsection{代码1}\n\\begin{Code}\n// LeetCode, Sort Colors\n// Counting Sort\n// 时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    void sortColors(vector<int>& A) {\n        int counts[3] = { 0 }; // 记录每个颜色出现的次数\n\n        for (int i = 0; i < A.size(); i++)\n            counts[A[i]]++;\n\n        for (int i = 0, index = 0; i < 3; i++)\n            for (int j = 0; j < counts[i]; j++)\n                A[index++] = i;\n\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{代码2}\n\\begin{Code}\n// LeetCode, Sort Colors\n// 双指针，时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    void sortColors(vector<int>& A) {\n        // 一个是red的index，一个是blue的index，两边往中间走\n        int red = 0, blue = A.size() - 1;\n\n        for (int i = 0; i < blue + 1;) {\n            if (A[i] == 0)\n                swap(A[i++], A[red++]);\n            else if (A[i] == 2)\n                swap(A[i], A[blue--]);\n            else\n                i++;\n        }\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{代码3}\n\\begin{Code}\n// LeetCode, Sort Colors\n// use partition()\n// 时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    void sortColors(vector<int>& nums) {\n        partition(partition(nums.begin(), nums.end(), bind1st(equal_to<int>(), 0)),\n                nums.end(), bind1st(equal_to<int>(), 1));\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{代码4}\n\\begin{Code}\n// LeetCode, Sort Colors\n// 重新实现 partition()\n// 时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    void sortColors(vector<int>& nums) {\n        partition(partition(nums.begin(), nums.end(), bind1st(equal_to<int>(), 0)),\n                 nums.end(), bind1st(equal_to<int>(), 1));\n    }\nprivate:\n    template<typename ForwardIterator, typename UnaryPredicate>\n    ForwardIterator partition(ForwardIterator first, ForwardIterator last,\n            UnaryPredicate pred) {\n        auto pos = first;\n\n        for (; first != last; ++first)\n            if (pred(*first))\n                swap(*first, *pos++);\n\n        return pos;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item First Missing Positive, 见 \\S \\ref{sec:first-missing-positive}\n\\myenddot\n"
  },
  {
    "path": "C++/chapStackAndQueue.tex",
    "content": "\\chapter{栈和队列}\n\n\n\\section{栈} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\\subsection{Valid Parentheses} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:valid-parentheses}\n\n\n\\subsubsection{描述}\nGiven a string containing just the characters \\code{'(', ')', '\\{', '\\}', '['} and \\code{']'}, determine if the input string is valid.\n\nThe brackets must close in the correct order, \\code{\"()\"} and \\code{\"()[]{}\"} are all valid but \\code{\"(]\"} and \\code{\"([)]\"} are not.\n\n\n\\subsubsection{分析}\n无\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Valid Parentheses\n// 时间复杂度O(n)，空间复杂度O(n)\nclass Solution {\npublic:\n    bool isValid (string const& s) {\n        string left = \"([{\";\n        string right = \")]}\";\n        stack<char> stk;\n\n        for (auto c : s) {\n            if (left.find(c) != string::npos) {\n                stk.push (c);\n            } else {\n                if (stk.empty () || stk.top () != left[right.find (c)])\n                    return false;\n                else\n                    stk.pop ();\n            }\n        }\n        return stk.empty();\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Generate Parentheses, 见 \\S \\ref{sec:generate-parentheses}\n\\item Longest Valid Parentheses, 见 \\S \\ref{sec:longest-valid-parentheses}\n\\myenddot\n\n\n\\subsection{Longest Valid Parentheses} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:longest-valid-parentheses}\n\n\n\\subsubsection{描述}\nGiven a string containing just the characters \\code{'('} and \\code{')'}, find the length of the longest valid (well-formed) parentheses substring.\n\nFor \\code{\"(()\"}, the longest valid parentheses substring is \\code{\"()\"}, which has length = 2.\n\nAnother example is \\code{\")()())\"}, where the longest valid parentheses substring is \\code{\"()()\"}, which has length = 4.\n\n\n\\subsubsection{分析}\n无\n\n\n\\subsubsection{使用栈}\n\\begin{Code}\n// LeetCode, Longest Valid Parenthese\n// 使用栈，时间复杂度O(n)，空间复杂度O(n)\nclass Solution {\npublic:\n    int longestValidParentheses(const string& s) {\n        int max_len = 0, last = -1; // the position of the last ')'\n        stack<int> lefts;  // keep track of the positions of non-matching '('s\n\n        for (int i = 0; i < s.size(); ++i) {\n            if (s[i] =='(') {\n                lefts.push(i);\n            } else {\n                if (lefts.empty()) {\n                    // no matching left\n                    last = i;\n                } else {\n                    // find a matching pair\n                    lefts.pop();\n                    if (lefts.empty()) {\n                        max_len = max(max_len, i-last);\n                    } else {\n                        max_len = max(max_len, i-lefts.top());\n                    }\n                }\n            }\n        }\n        return max_len;\n    }\n};\n\\end{Code}\n\n\\subsubsection{Dynamic Programming, One Pass}\n\\begin{Code}\n// LeetCode, Longest Valid Parenthese\n// 时间复杂度O(n)，空间复杂度O(n)\n// @author 一只杰森(http://weibo.com/wjson)\nclass Solution {\npublic:\n    int longestValidParentheses(const string& s) {\n        vector<int> f(s.size(), 0);\n        int ret = 0;\n        for (int i = s.size() - 2; i >= 0; --i) {\n            int match = i + f[i + 1] + 1;\n            // case: \"((...))\"\n            if (s[i] == '(' && match < s.size() && s[match] == ')') {\n                f[i] = f[i + 1] + 2;\n                // if a valid sequence exist afterwards \"((...))()\"\n                if (match + 1 < s.size()) f[i] += f[match + 1];\n            }\n            ret = max(ret, f[i]);\n        }\n        return ret;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{两遍扫描}\n\\begin{Code}\n// LeetCode, Longest Valid Parenthese\n// 两遍扫描，时间复杂度O(n)，空间复杂度O(1)\n// @author 曹鹏(http://weibo.com/cpcs)\nclass Solution {\npublic:\n    int longestValidParentheses(const string& s) {\n        int answer = 0, depth = 0, start = -1;\n        for (int i = 0; i < s.size(); ++i) {\n            if (s[i] == '(') {\n                ++depth;\n            } else {\n                --depth;\n                if (depth < 0) {\n                    start = i;\n                    depth = 0;\n                } else if (depth == 0) {\n                    answer = max(answer, i - start);\n                }\n            } \n        }\n\n        depth = 0;\n        start = s.size();\n        for (int i = s.size() - 1; i >= 0; --i) {\n            if (s[i] == ')') {\n                ++depth;\n            } else {\n                --depth;\n                if (depth < 0) {\n                    start = i;\n                    depth = 0;\n                } else if (depth == 0) {\n                    answer = max(answer, start - i);\n                }\n            } \n        }\n        return answer;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Valid Parentheses, 见 \\S \\ref{sec:valid-parentheses}\n\\item Generate Parentheses, 见 \\S \\ref{sec:generate-parentheses}\n\\myenddot\n\n\n\\subsection{Largest Rectangle in Histogram} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:largest-rectangle-in-histogram}\n\n\n\\subsubsection{描述}\nGiven $n$ non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.\n\n\\begin{center}\n\\includegraphics[width=120pt]{histogram.png}\\\\\n\\figcaption{Above is a histogram where width of each bar is 1, given height = \\fn{[2,1,5,6,2,3]}.}\\label{fig:histogram}\n\\end{center}\n\n\\begin{center}\n\\includegraphics[width=120pt]{histogram-area.png}\\\\\n\\figcaption{The largest rectangle is shown in the shaded area, which has area = 10 unit.}\\label{fig:histogram-area}\n\\end{center}\n\nFor example,\nGiven height = \\fn{[2,1,5,6,2,3]},\nreturn 10.\n\n\n\\subsubsection{分析}\n简单的，类似于 Container With Most Water(\\S \\ref{sec:container-with-most-water})，对每个柱子，左右扩展，直到碰到比自己矮的，计算这个矩形的面积，用一个变量记录最大的面积，复杂度$O(n^2)$，会超时。\n\n如图\\S \\ref{fig:histogram-area}所示，从左到右处理直方，当$i=4$时，小于当前栈顶（即直方3），对于直方3，无论后面还是前面的直方，都不可能得到比目前栈顶元素更高的高度了，处理掉直方3（计算从直方3到直方4之间的矩形的面积，然后从栈里弹出）；对于直方2也是如此；直到碰到比直方4更矮的直方1。\n\n这就意味着，可以维护一个递增的栈，每次比较栈顶与当前元素。如果当前元素大于栈顶元素，则入栈，否则合并现有栈，直至栈顶元素小于当前元素。结尾时入栈元素0，重复合并一次。\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Largest Rectangle in Histogram\n// 时间复杂度O(n)，空间复杂度O(n)\nclass Solution {\npublic:\n    int largestRectangleArea(vector<int> &height) {\n        stack<int> s;\n        height.push_back(0);\n        int result = 0;\n        for (int i = 0; i < height.size(); ) {\n            if (s.empty() || height[i] > height[s.top()])\n                s.push(i++);\n            else {\n                int tmp = s.top();\n                s.pop();\n                result = max(result,\n                        height[tmp] * (s.empty() ? i : i - s.top() - 1));\n            }\n        }\n        return result;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Trapping Rain Water, 见 \\S \\ref{sec:trapping-rain-water}\n\\item Container With Most Water, 见 \\S \\ref{sec:container-with-most-water}\n\\myenddot\n\n\n\\subsection{Evaluate Reverse Polish Notation} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:evaluate-reverse-polish-notation}\n\n\n\\subsubsection{描述}\nEvaluate the value of an arithmetic expression in Reverse Polish Notation.\n\nValid operators are \\fn{+, -, *, /}. Each operand may be an integer or another expression.\n\nSome examples:\n\\begin{Code}\n  [\"2\", \"1\", \"+\", \"3\", \"*\"] -> ((2 + 1) * 3) -> 9\n  [\"4\", \"13\", \"5\", \"/\", \"+\"] -> (4 + (13 / 5)) -> 6\n\\end{Code}\n\n\n\\subsubsection{分析}\n无\n\n\n\\subsubsection{递归版}\n\\begin{Code}\n// LeetCode, Evaluate Reverse Polish Notation\n// 递归，时间复杂度O(n)，空间复杂度O(logn)\nclass Solution {\npublic:\n    int evalRPN(vector<string> &tokens) {\n        int x, y;\n        auto token = tokens.back();  tokens.pop_back();\n        if (is_operator(token))  {\n            y = evalRPN(tokens);\n            x = evalRPN(tokens);\n            if (token[0] == '+')       x += y;\n            else if (token[0] == '-')  x -= y;\n            else if (token[0] == '*')  x *= y;\n            else                       x /= y;\n        } else  {\n            size_t i;\n            x = stoi(token, &i);\n        }\n        return x;\n    }\nprivate:\n    bool is_operator(const string &op) {\n        return op.size() == 1 && string(\"+-*/\").find(op) != string::npos;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{迭代版}\n\\begin{Code}\n// LeetCode, Max Points on a Line\n// 迭代，时间复杂度O(n)，空间复杂度O(logn)\nclass Solution {\npublic:\n    int evalRPN(vector<string> &tokens) {\n        stack<string> s;\n        for (auto token : tokens) {\n            if (!is_operator(token)) {\n                s.push(token);\n            } else {\n                int y = stoi(s.top());\n                s.pop();\n                int x = stoi(s.top());\n                s.pop();\n                if (token[0] == '+')       x += y;\n                else if (token[0] == '-')  x -= y;\n                else if (token[0] == '*')  x *= y;\n                else                       x /= y;\n                s.push(to_string(x));\n            }\n        }\n        return stoi(s.top());\n    }\nprivate:\n    bool is_operator(const string &op) {\n        return op.size() == 1 && string(\"+-*/\").find(op) != string::npos;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item 无\n\\myenddot\n\n\n\\section{队列} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n"
  },
  {
    "path": "C++/chapString.tex",
    "content": "\\chapter{字符串}\n\n\n\\section{Valid Palindrome} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:valid-palindrome}\n\n\n\\subsubsection{描述}\nGiven a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.\n\nFor example,\\\\\n\\code{\"A man, a plan, a canal: Panama\"} is a palindrome.\\\\\n\\code{\"race a car\"} is not a palindrome.\n\nNote:\nHave you consider that the string might be empty? This is a good question to ask during an interview.\n\nFor the purpose of this problem, we define empty string as valid palindrome.\n\n\n\\subsubsection{分析}\n无\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// Leet Code, Valid Palindrome\n// 时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    bool isPalindrome(string s) {\n        transform(s.begin(), s.end(), s.begin(), ::tolower);\n        auto left = s.begin(), right = prev(s.end());\n        while (left < right) {\n            if (!::isalnum(*left))  ++left;\n            else if (!::isalnum(*right)) --right;\n            else if (*left != *right) return false;\n            else { left++, right--; }\n        }\n        return true;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Palindrome Number, 见 \\S \\ref{sec:palindrome-number}\n\\myenddot\n\n\n\\section{Implement strStr()} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:strstr}\n\n\n\\subsubsection{描述}\nImplement strStr().\n\nReturns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.\n\n\n\\subsubsection{分析}\n暴力算法的复杂度是 $O(m*n)$，代码如下。更高效的的算法有KMP算法、Boyer-Mooer算法和Rabin-Karp算法。面试中暴力算法足够了，一定要写得没有BUG。\n\n\n\\subsubsection{暴力匹配}\n\\begin{Code}\n// LeetCode, Implement strStr()\n// 暴力解法，时间复杂度O(N*M)，空间复杂度O(1)\nclass Solution {\npublic:\n    int strStr(const string& haystack, const string& needle) {\n        if (needle.empty()) return 0;\n\n        const int N = haystack.size() - needle.size() + 1;\n        for (int i = 0; i < N; i++) {\n            int j = i;\n            int k = 0;\n            while (j < haystack.size() && k < needle.size() && haystack[j] == needle[k]) {\n                j++;\n                k++;\n            }\n            if (k == needle.size()) return i;\n        }\n        return -1;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{KMP}\n\\begin{Code}\n// LeetCode, Implement strStr()\n// KMP，时间复杂度O(N+M)，空间复杂度O(M)\nclass Solution {\npublic:\n    int strStr(const string& haystack, const string& needle) {\n        return kmp(haystack.c_str(), needle.c_str());\n    }\nprivate:\n    /*\n     * @brief 计算部分匹配表，即next数组.\n     *\n     * @param[in] pattern 模式串\n     * @param[out] next next数组\n     * @return 无\n     */\n    static void compute_prefix(const char *pattern, int next[]) {\n        int i;\n        int j = -1;\n        const int m = strlen(pattern);\n\n        next[0] = j;\n        for (i = 1; i < m; i++) {\n            while (j > -1 && pattern[j + 1] != pattern[i]) j = next[j];\n\n            if (pattern[i] == pattern[j + 1]) j++;\n            next[i] = j;\n        }\n    }\n\n    /*\n     * @brief KMP算法.\n     *\n     * @param[in] text 文本\n     * @param[in] pattern 模式串\n     * @return 成功则返回第一次匹配的位置，失败则返回-1\n     */\n    static int kmp(const char *text, const char *pattern) {\n        int i;\n        int j = -1;\n        const int n = strlen(text);\n        const int m = strlen(pattern);\n        if (n == 0 && m == 0) return 0; /* \"\",\"\" */\n        if (m == 0) return 0;  /* \"a\",\"\" */\n        int *next = (int*)malloc(sizeof(int) * m);\n\n        compute_prefix(pattern, next);\n\n        for (i = 0; i < n; i++) {\n            while (j > -1 && pattern[j + 1] != text[i]) j = next[j];\n\n            if (text[i] == pattern[j + 1]) j++;\n            if (j == m - 1) {\n                free(next);\n                return i-j;\n            }\n        }\n\n        free(next);\n        return -1;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item String to Integer (atoi) ，见 \\S \\ref{sec:string-to-integer}\n\\myenddot\n\n\n\\section{String to Integer (atoi)} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:string-to-integer}\n\n\n\\subsubsection{描述}\nImplement \\fn{atoi} to convert a string to an integer.\n\n\\textbf{Hint}: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.\n\n\\textbf{Notes}: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.\n\n\\textbf{Requirements for atoi}:\n\nThe function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.\n\nThe string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.\n\nIf the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.\n\nIf no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, \\code{INT_MAX (2147483647)} or \\code{INT_MIN (-2147483648)} is returned.\n\n\\subsubsection{分析}\n细节题。注意几个测试用例：\n\\begin{enumerate}\n\\item 不规则输入，但是有效，\"-3924x8fc\"， \"  +  413\",\n\\item 无效格式，\" ++c\", \" ++1\"\n\\item 溢出数据，\"2147483648\"\n\\end{enumerate}\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, String to Integer (atoi)\n// 时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    int myAtoi(const string &str) {\n        int num = 0;\n        int sign = 1;\n        const int n = str.length();\n        int i = 0;\n\n        while (str[i] == ' ' && i < n) i++;\n\n        if (str[i] == '+') {\n            i++;\n        } else if (str[i] == '-') {\n            sign = -1;\n            i++;\n        }\n\n        for (; i < n; i++) {\n            if (str[i] < '0' || str[i] > '9')\n                break;\n            if (num > INT_MAX / 10 ||\n                            (num == INT_MAX / 10 &&\n                                    (str[i] - '0') > INT_MAX % 10)) {\n                return sign == -1 ? INT_MIN : INT_MAX;\n            }\n            num = num * 10 + str[i] - '0';\n        }\n        return num * sign;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Implement strStr() ，见 \\S \\ref{sec:strstr}\n\\myenddot\n\n\n\\section{Add Binary} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:add-binary}\n\n\n\\subsubsection{描述}\nGiven two binary strings, return their sum (also a binary string).\n\nFor example,\n\\begin{Code}\na = \"11\"\nb = \"1\"\n\\end{Code}\nReturn {\\small \\fontspec{Latin Modern Mono} \"100\"}.\n\n\n\\subsubsection{分析}\n无\n\n\n\\subsubsection{代码}\n\\begin{Code}\n//LeetCode, Add Binary\n// 时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    string addBinary(string a, string b) {\n        string result;\n        const size_t n = a.size() > b.size() ? a.size() : b.size();\n        reverse(a.begin(), a.end());\n        reverse(b.begin(), b.end());\n        int carry = 0;\n        for (size_t i = 0; i < n; i++) {\n            const int ai = i < a.size() ? a[i] - '0' : 0;\n            const int bi = i < b.size() ? b[i] - '0' : 0;\n            const int val = (ai + bi + carry) % 2;\n            carry = (ai + bi + carry) / 2;\n            result.insert(result.begin(), val + '0');\n        }\n        if (carry == 1) {\n            result.insert(result.begin(), '1');\n        }\n        return result;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Add Two Numbers, 见 \\S \\ref{sec:add-two-numbers}\n\\myenddot\n\n\n\\section{Longest Palindromic Substring} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:longest-palindromic-substring}\n\n\n\\subsubsection{描述}\nGiven a string $S$, find the longest palindromic substring in $S$. You may assume that the maximum length of $S$ is 1000, and there exists one unique longest palindromic substring.\n\n\n\\subsubsection{分析}\n最长回文子串，非常经典的题。\n\n思路一：暴力枚举，以每个元素为中间元素，同时从左右出发，复杂度$O(n^2)$。\n\n思路二：记忆化搜索，复杂度$O(n^2)$。设\\fn{f[i][j]} 表示[i,j]之间的最长回文子串，递推方程如下：\n\\begin{Code}\nf[i][j] = if (i == j) S[i]\n          if (S[i] == S[j] && f[i+1][j-1] == S[i+1][j-1]) S[i][j]\n          else max(f[i+1][j-1], f[i][j-1], f[i+1][j])\n\\end{Code}\n\n思路三：动规，复杂度$O(n^2)$。设状态为\\fn{f(i,j)}，表示区间[i,j]是否为回文串，则状态转移方程为\n$$\nf(i,j)=\\begin{cases}\ntrue & ,i=j\\\\\nS[i]=S[j] & , j = i + 1 \\\\\nS[i]=S[j] \\text{ and } f(i+1, j-1) & , j > i + 1\n\\end{cases}\n$$\n\n思路四：Manacher’s Algorithm, 复杂度$O(n)$。详细解释见 \\myurl{http://leetcode.com/2011/11/longest-palindromic-substring-part-ii.html} 。\n\n\n\\subsubsection{备忘录法}\n\\begin{Code}\n// LeetCode, Longest Palindromic Substring\n// 备忘录法，会超时\n// 时间复杂度O(n^2)，空间复杂度O(n^2)\ntypedef string::const_iterator Iterator;\n\nnamespace std {\ntemplate<>\nstruct hash<pair<Iterator, Iterator>> {\n    size_t operator()(pair<Iterator, Iterator> const& p) const {\n        return ((size_t) &(*p.first)) ^ ((size_t) &(*p.second));\n    }\n};\n}\n\nclass Solution {\npublic:\n    string longestPalindrome(string const& s) {\n        cache.clear();\n        return cachedLongestPalindrome(s.begin(), s.end());\n    }\n\nprivate:\n    unordered_map<pair<Iterator, Iterator>, string> cache;\n\n    string longestPalindrome(Iterator first, Iterator last) {\n        size_t length = distance(first, last);\n\n        if (length < 2) return string(first, last);\n\n        auto s = cachedLongestPalindrome(next(first), prev(last));\n\n        if (s.length() == length - 2 && *first == *prev(last))\n            return string(first, last);\n\n        auto s1 = cachedLongestPalindrome(next(first), last);\n        auto s2 = cachedLongestPalindrome(first, prev(last));\n\n        // return max(s, s1, s2)\n        if (s.size() > s1.size()) return s.size() > s2.size() ? s : s2;\n        else return s1.size() > s2.size() ? s1 : s2;\n    }\n\n    string cachedLongestPalindrome(Iterator first, Iterator last) {\n        auto key = make_pair(first, last);\n        auto pos = cache.find(key);\n\n        if (pos != cache.end()) return pos->second;\n        else return cache[key] = longestPalindrome(first, last);\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{动规}\n\\begin{Code}\n// LeetCode, Longest Palindromic Substring\n// 动规，时间复杂度O(n^2)，空间复杂度O(n^2)\nclass Solution {\npublic:\n    string longestPalindrome(const string& s) {\n        const int n = s.size();\n        bool f[n][n];\n        fill_n(&f[0][0], n * n, false);\n        // 用 vector 会超时\n        //vector<vector<bool> > f(n, vector<bool>(n, false));\n        size_t max_len = 1, start = 0;  // 最长回文子串的长度，起点\n\n        for (size_t i = 0; i < s.size(); i++) {\n            f[i][i] = true;\n            for (size_t j = 0; j < i; j++) {  // [j, i]\n                f[j][i] = (s[j] == s[i] && (i - j < 2 || f[j + 1][i - 1]));\n                if (f[j][i] && max_len < (i - j + 1)) {\n                    max_len = i - j + 1;\n                    start = j;\n                }\n            }\n        }\n        return s.substr(start, max_len);\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{Manacher’s Algorithm}\n\\begin{Code}\n// LeetCode, Longest Palindromic Substring\n// Manacher’s Algorithm\n// 时间复杂度O(n)，空间复杂度O(n)\nclass Solution {\npublic:\n    // Transform S into T.\n    // For example, S = \"abba\", T = \"^#a#b#b#a#$\".\n    // ^ and $ signs are sentinels appended to each end to avoid bounds checking\n    string preProcess(const string& s) {\n        int n = s.length();\n        if (n == 0) return \"^$\";\n\n        string ret = \"^\";\n        for (int i = 0; i < n; i++) ret += \"#\" + s.substr(i, 1);\n\n        ret += \"#$\";\n        return ret;\n    }\n\n    string longestPalindrome(string s) {\n        string T = preProcess(s);\n        const int n = T.length();\n        // 以T[i]为中心，向左/右扩张的长度，不包含T[i]自己，\n        // 因此 P[i]是源字符串中回文串的长度\n        int P[n];\n        int C = 0, R = 0;\n\n        for (int i = 1; i < n - 1; i++) {\n            int i_mirror = 2 * C - i; // equals to i' = C - (i-C)\n\n            P[i] = (R > i) ? min(R - i, P[i_mirror]) : 0;\n\n            // Attempt to expand palindrome centered at i\n            while (T[i + 1 + P[i]] == T[i - 1 - P[i]])\n                P[i]++;\n\n            // If palindrome centered at i expand past R,\n            // adjust center based on expanded palindrome.\n            if (i + P[i] > R) {\n                C = i;\n                R = i + P[i];\n            }\n        }\n\n        // Find the maximum element in P.\n        int max_len = 0;\n        int center_index = 0;\n        for (int i = 1; i < n - 1; i++) {\n            if (P[i] > max_len) {\n                max_len = P[i];\n                center_index = i;\n            }\n        }\n\n        return s.substr((center_index - 1 - max_len) / 2, max_len);\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item 无\n\\myenddot\n\n\n\\section{Regular Expression Matching} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:regular-expression-matching}\n\n\n\\subsubsection{描述}\nImplement regular expression matching with support for \\fn{'.'} and \\fn{'*'}.\n\n\\fn{'.'} Matches any single character.\n\\fn{'*'} Matches zero or more of the preceding element.\n\nThe matching should cover the entire input string (not partial).\n\nThe function prototype should be:\n\\begin{Code}\nbool isMatch(const char *s, const char *p)\n\\end{Code}\n\nSome examples:\n\\begin{Code}\nisMatch(\"aa\",\"a\") → false\nisMatch(\"aa\",\"aa\") → true\nisMatch(\"aaa\",\"aa\") → false\nisMatch(\"aa\", \"a*\") → true\nisMatch(\"aa\", \".*\") → true\nisMatch(\"ab\", \".*\") → true\nisMatch(\"aab\", \"c*a*b\") → true\n\\end{Code}\n\n\n\\subsubsection{分析}\n这是一道很有挑战的题。\n\n\n\\subsubsection{递归版}\n\\begin{Code}\n// LeetCode, Regular Expression Matching\n// 递归版，时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    bool isMatch(const string& s, const string& p) {\n        return isMatch(s.c_str(), p.c_str());\n    }\nprivate:\n    bool isMatch(const char *s, const char *p) {\n        if (*p == '\\0') return *s == '\\0';\n\n        // next char is not '*', then must match current character\n        if (*(p + 1) != '*') {\n            if (*p == *s || (*p == '.' && *s != '\\0'))\n                return isMatch(s + 1, p + 1);\n            else\n                return false;\n        } else { // next char is '*'\n            while (*p == *s || (*p == '.' && *s != '\\0')) {\n                if (isMatch(s, p + 2))\n                    return true;\n                s++;\n            }\n            return isMatch(s, p + 2);\n        }\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{迭代版}\n\\begin{Code}\n\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Wildcard Matching, 见 \\S \\ref{sec:wildcard-matching}\n\\myenddot\n\n\n\\section{Wildcard Matching} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:wildcard-matching}\n\n\n\\subsubsection{描述}\nImplement wildcard pattern matching with support for \\fn{'?'} and \\fn{'*'}.\n\n\\fn{'?'} Matches any single character.\n\\fn{'*'} Matches any sequence of characters (including the empty sequence).\n\nThe matching should cover the entire input string (not partial).\n\nThe function prototype should be:\n\\begin{Code}\nbool isMatch(const char *s, const char *p)\n\\end{Code}\n\nSome examples:\n\\begin{Code}\nisMatch(\"aa\",\"a\") → false\nisMatch(\"aa\",\"aa\") → true\nisMatch(\"aaa\",\"aa\") → false\nisMatch(\"aa\", \"*\") → true\nisMatch(\"aa\", \"a*\") → true\nisMatch(\"ab\", \"?*\") → true\nisMatch(\"aab\", \"c*a*b\") → false\n\\end{Code}\n\n\n\\subsubsection{分析}\n跟上一题很类似。\n\n主要是\\fn{'*'}的匹配问题。\\fn{p}每遇到一个\\fn{'*'}，就保留住当前\\fn{'*'}的坐标和\\fn{s}的坐标，然后\\fn{s}从前往后扫描，如果不成功，则\\fn{s++}，重新扫描。\n\n\n\\subsubsection{递归版}\n\\begin{Code}\n// LeetCode, Wildcard Matching\n// 递归版，会超时，用于帮助理解题意\n// 时间复杂度O(n!*m!)，空间复杂度O(n)\nclass Solution {\npublic:\n    bool isMatch(const string& s, const string& p) {\n        return isMatch(s.c_str(), p.c_str());\n    }\nprivate:\n    bool isMatch(const char *s, const char *p) {\n        if (*p == '*') {\n            while (*p == '*') ++p;  //skip continuous '*'\n            if (*p == '\\0') return true;\n            while (*s != '\\0' && !isMatch(s, p)) ++s;\n\n            return *s != '\\0';\n        }\n        else if (*p == '\\0' || *s == '\\0') return *p == *s;\n        else if (*p == *s || *p == '?') return isMatch(++s, ++p);\n        else return false;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{迭代版}\n\\begin{Code}\n// LeetCode, Wildcard Matching\n// 迭代版，时间复杂度O(n*m)，空间复杂度O(1)\nclass Solution {\npublic:\n    bool isMatch(const string& s, const string& p) {\n        return isMatch(s.c_str(), p.c_str());\n    }\nprivate:\n    bool isMatch(const char *s, const char *p) {\n        bool star = false;\n        const char *str, *ptr;\n        for (str = s, ptr = p; *str != '\\0'; str++, ptr++) {\n            switch (*ptr) {\n            case '?':\n                break;\n            case '*':\n                star = true;\n                s = str, p = ptr;\n                while (*p == '*') p++;  //skip continuous '*'\n                if (*p == '\\0') return true;\n                str = s - 1;\n                ptr = p - 1;\n                break;\n            default:\n                if (*str != *ptr) {\n                    // 如果前面没有'*'，则匹配不成功\n                    if (!star) return false;\n                    s++;\n                    str = s - 1;\n                    ptr = p - 1;\n                }\n            }\n        }\n        while (*ptr == '*') ptr++;\n        return (*ptr == '\\0');\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Regular Expression Matching, 见 \\S \\ref{sec:regular-expression-matching}\n\\myenddot\n\n\n\\section{Longest Common Prefix} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:longest-common-prefix}\n\n\n\\subsubsection{描述}\nWrite a function to find the longest common prefix string amongst an array of strings.\n\n\n\\subsubsection{分析}\n从位置0开始，对每一个位置比较所有字符串，直到遇到一个不匹配。\n\n\n\\subsubsection{纵向扫描}\n\\begin{Code}\n// LeetCode, Longest Common Prefix\n// 纵向扫描，从位置0开始，对每一个位置比较所有字符串，直到遇到一个不匹配\n// 时间复杂度O(n1+n2+...)\n// @author 周倩 (http://weibo.com/zhouditty)\nclass Solution {\npublic:\n    string longestCommonPrefix(vector<string> &strs) {\n        if (strs.empty()) return \"\";\n\n        for (int idx = 0; idx < strs[0].size(); ++idx) { // 纵向扫描\n            for (int i = 1; i < strs.size(); ++i) {\n                if (strs[i][idx] != strs[0][idx]) return strs[0].substr(0,idx);\n            }\n        }\n        return strs[0];\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{横向扫描}\n\\begin{Code}\n// LeetCode, Longest Common Prefix\n// 横向扫描，每个字符串与第0个字符串，从左到右比较，直到遇到一个不匹配，\n// 然后继续下一个字符串\n// 时间复杂度O(n1+n2+...)\nclass Solution {\npublic:\n    string longestCommonPrefix(vector<string> &strs) {\n        if (strs.empty()) return \"\";\n\n        int right_most = strs[0].size() - 1;\n        for (size_t i = 1; i < strs.size(); i++)\n            for (int j = 0; j <= right_most; j++)\n                if (strs[i][j] != strs[0][j])  // 不会越界，请参考string::[]的文档\n                    right_most = j - 1;\n\n        return strs[0].substr(0, right_most + 1);\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item 无\n\\myenddot\n\n\n\\section{Valid Number} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:valid-number}\n\n\n\\subsubsection{描述}\nValidate if a given string is numeric.\n\nSome examples:\n\\begin{Code}\n\"0\" => true\n\" 0.1 \" => true\n\"abc\" => false\n\"1 a\" => false\n\"2e10\" => true\n\\end{Code}\n\nNote: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.\n\n\n\\subsubsection{分析}\n细节实现题。\n\n本题的功能与标准库中的\\fn{strtod()}功能类似。\n\n\n\\subsubsection{有限自动机}\n\\begin{Code}\n// LeetCode, Valid Number\n// @author 龚陆安 (http://weibo.com/luangong)\n// finite automata，时间复杂度O(n)，空间复杂度O(n)\nclass Solution {\npublic:\n    bool isNumber(const string& s) {\n        enum InputType {\n            INVALID,    // 0\n            SPACE,      // 1\n            SIGN,       // 2\n            DIGIT,      // 3\n            DOT,        // 4\n            EXPONENT,   // 5\n            NUM_INPUTS  // 6\n        };\n        const int transitionTable[][NUM_INPUTS] = {\n                -1, 0, 3, 1, 2, -1, // next states for state 0\n                -1, 8, -1, 1, 4, 5,     // next states for state 1\n                -1, -1, -1, 4, -1, -1,     // next states for state 2\n                -1, -1, -1, 1, 2, -1,     // next states for state 3\n                -1, 8, -1, 4, -1, 5,     // next states for state 4\n                -1, -1, 6, 7, -1, -1,     // next states for state 5\n                -1, -1, -1, 7, -1, -1,     // next states for state 6\n                -1, 8, -1, 7, -1, -1,     // next states for state 7\n                -1, 8, -1, -1, -1, -1,     // next states for state 8\n                };\n\n        int state = 0;\n        for (auto ch : s) {\n            InputType inputType = INVALID;\n            if (isspace(ch))\n                inputType = SPACE;\n            else if (ch == '+' || ch == '-')\n                inputType = SIGN;\n            else if (isdigit(ch))\n                inputType = DIGIT;\n            else if (ch == '.')\n                inputType = DOT;\n            else if (ch == 'e' || ch == 'E')\n                inputType = EXPONENT;\n\n            // Get next state from current state and input symbol\n            state = transitionTable[state][inputType];\n\n            // Invalid input\n            if (state == -1) return false;\n        }\n        // If the current state belongs to one of the accepting (final) states,\n        // then the number is valid\n        return state == 1 || state == 4 || state == 7 || state == 8;\n\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{使用strtod()}\n\\begin{Code}\n// LeetCode, Valid Number\n// @author 连城 (http://weibo.com/lianchengzju)\n// 偷懒，直接用 strtod()，时间复杂度O(n)\nclass Solution {\npublic:\n    bool isNumber (const string& s) {\n        return isNumber(s.c_str());\n    }\nprivate:\n    bool isNumber (char const* s) {\n        char* endptr;\n        strtod (s, &endptr);\n\n        if (endptr == s) return false;\n\n        for (; *endptr; ++endptr)\n            if (!isspace (*endptr)) return false;\n\n        return true;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item 无\n\\myenddot\n\n\n\\section{Integer to Roman} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:integer-to-roman}\n\n\n\\subsubsection{描述}\nGiven an integer, convert it to a roman numeral.\n\nInput is guaranteed to be within the range from 1 to 3999.\n\n\n\\subsubsection{分析}\n无\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Integer to Roman\n// 时间复杂度O(num)，空间复杂度O(1)\nclass Solution {\npublic:\n    string intToRoman(int num) {\n        const int radix[] = {1000, 900, 500, 400, 100, 90,\n                50, 40, 10, 9, 5, 4, 1};\n        const string symbol[] = {\"M\", \"CM\", \"D\", \"CD\", \"C\", \"XC\",\n                \"L\", \"XL\", \"X\", \"IX\", \"V\", \"IV\", \"I\"};\n\n        string roman;\n        for (size_t i = 0; num > 0; ++i) {\n            int count = num / radix[i];\n            num %= radix[i];\n            for (; count > 0; --count) roman += symbol[i];\n        }\n        return roman;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Roman to Integer, 见 \\S \\ref{sec:roman-to-integer}\n\\myenddot\n\n\n\\section{Roman to Integer} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:roman-to-integer}\n\n\n\\subsubsection{描述}\nGiven a roman numeral, convert it to an integer.\n\nInput is guaranteed to be within the range from 1 to 3999.\n\n\n\\subsubsection{分析}\n从前往后扫描，用一个临时变量记录分段数字。\n\n如果当前比前一个大，说明这一段的值应该是当前这个值减去上一个值。比如\\fn{IV = 5 – 1}；否则，将当前值加入到结果中，然后开始下一段记录。比如\\fn{VI = 5 + 1, II=1+1}\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Roman to Integer\n// 时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    inline int map(const char c) {\n        switch (c) {\n        case 'I': return 1;\n        case 'V': return 5;\n        case 'X': return 10;\n        case 'L': return 50;\n        case 'C': return 100;\n        case 'D': return 500;\n        case 'M': return 1000;\n        default: return 0;\n        }\n    }\n\n    int romanToInt(const string& s) {\n        int result = 0;\n        for (size_t i = 0; i < s.size(); i++) {\n            if (i > 0 && map(s[i]) > map(s[i - 1])) {\n                result += (map(s[i]) - 2 * map(s[i - 1]));\n            } else {\n                result += map(s[i]);\n            }\n        }\n        return result;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Integer to Roman, 见 \\S \\ref{sec:integer-to-roman}\n\\myenddot\n\n\n\\section{Count and Say} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:count-and-say}\n\n\n\\subsubsection{描述}\nThe count-and-say sequence is the sequence of integers beginning as follows:\n\\begin{Code}\n1, 11, 21, 1211, 111221, ...\n\\end{Code}\n\n\\fn{1} is read off as \\fn{\"one 1\"} or \\fn{11}.\n\n\\fn{11} is read off as \\fn{\"two 1s\"} or \\fn{21}.\n\n\\fn{21} is read off as \\fn{\"one 2\"}, then \\fn{\"one 1\"} or \\fn{1211}.\n\nGiven an integer $n$, generate the nth sequence.\n\nNote: The sequence of integers will be represented as a string.\n\n\n\\subsubsection{分析}\n模拟。\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Count and Say\n// @author 连城 (http://weibo.com/lianchengzju)\n// 时间复杂度O(n^2)，空间复杂度O(n)\nclass Solution {\npublic:\n    string countAndSay(int n) {\n        string s(\"1\");\n\n        while (--n)\n            s = getNext(s);\n\n        return s;\n    }\n\n    string getNext(const string &s) {\n        stringstream ss;\n\n        for (auto i = s.begin(); i != s.end(); ) {\n            auto j = find_if(i, s.end(), bind1st(not_equal_to<char>(), *i));\n            ss << distance(i, j) << *i;\n            i = j;\n        }\n\n        return ss.str();\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item 无\n\\myenddot\n\n\n\\section{Anagrams} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:anagrams}\n\n\n\\subsubsection{描述}\nGiven an array of strings, return all groups of strings that are anagrams.\n\nNote: All inputs will be in lower-case.\n\n\n\\subsubsection{分析}\nAnagram（回文构词法）是指打乱字母顺序从而得到新的单词，比如 \\fn{\"dormitory\"} 打乱字母顺序会变成 \\fn{\"dirty room\"} ，\\fn{\"tea\"} 会变成\\fn{\"eat\"}。\n\n回文构词法有一个特点：单词里的字母的种类和数目没有改变，只是改变了字母的排列顺序。因此，将几个单词按照字母顺序排序后，若它们相等，则它们属于同一组 anagrams 。\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Anagrams\n// 时间复杂度O(n)，空间复杂度O(n)\nclass Solution {\npublic:\n    vector<string> anagrams(vector<string> &strs) {\n        unordered_map<string, vector<string> > group;\n        for (const auto &s : strs) {\n            string key = s;\n            sort(key.begin(), key.end());\n            group[key].push_back(s);\n        }\n\n        vector<string> result;\n        for (auto it = group.cbegin(); it != group.cend(); it++) {\n            if (it->second.size() > 1)\n                result.insert(result.end(), it->second.begin(), it->second.end());\n        }\n        return result;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item 无\n\\myenddot\n\n\n\\section{Simplify Path} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:simplify-path}\n\n\n\\subsubsection{描述}\nGiven an absolute path for a file (Unix-style), simplify it.\n\nFor example, \\\\\npath = \\fn{\"/home/\"}, => \\fn{\"/home\"} \\\\\npath = \\fn{\"/a/./b/../../c/\"}, => \\fn{\"/c\"} \\\\\n\nCorner Cases:\n\\begindot\n\\item Did you consider the case where path = \\fn{\"/../\"}? \nIn this case, you should return \\fn{\"/\"}.\n\\item \nAnother corner case is the path might contain multiple slashes \\fn{'/'} together, such as \\fn{\"/home//foo/\"}.\nIn this case, you should ignore redundant slashes and return \\fn{\"/home/foo\"}.\n\\myenddot\n\n\n\\subsubsection{分析}\n很有实际价值的题目。\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Simplify Path\n// 时间复杂度O(n)，空间复杂度O(n)\nclass Solution {\npublic:\n    string simplifyPath(const string& path) {\n        vector<string> dirs; // 当做栈\n\n        for (auto i = path.begin(); i != path.end();) {\n            ++i;\n\n            auto j = find(i, path.end(), '/');\n            auto dir = string(i, j);\n\n            if (!dir.empty() && dir != \".\") {// 当有连续 '///'时，dir 为空\n                if (dir == \"..\") {\n                    if (!dirs.empty())\n                        dirs.pop_back();\n                } else\n                    dirs.push_back(dir);\n            }\n\n            i = j;\n        }\n\n        stringstream out;\n        if (dirs.empty()) {\n            out << \"/\";\n        } else {\n            for (auto dir : dirs)\n                out << '/' << dir;\n        }\n\n        return out.str();\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item 无\n\\myenddot\n\n\n\\section{Length of Last Word} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:length-of-last-word}\n\n\n\\subsubsection{描述}\nGiven a string s consists of upper/lower-case alphabets and empty space characters \\fn{' '}, return the length of last word in the string.\n\nIf the last word does not exist, return 0.\n\nNote: A word is defined as a character sequence consists of non-space characters only.\n\nFor example, \nGiven \\fn{s = \"Hello World\"},\nreturn 5.\n\n\n\\subsubsection{分析}\n细节实现题。\n\n\n\\subsubsection{用 STL}\n\\begin{Code}\n// LeetCode, Length of Last Word\n// 偷懒，用 STL\n// 时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    int lengthOfLastWord(const string& s) {\n        auto first = find_if(s.rbegin(), s.rend(), ::isalpha);\n        auto last = find_if_not(first, s.rend(), ::isalpha);\n        return distance(first, last);\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{顺序扫描}\n\\begin{Code}\n// LeetCode, Length of Last Word\n// 顺序扫描，记录每个 word 的长度\n// 时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    int lengthOfLastWord(const string& s) {\n        return lengthOfLastWord(s.c_str());\n    }\nprivate:\n    int lengthOfLastWord(const char *s) {\n        int len = 0;\n        while (*s) {\n            if (*s++ != ' ')\n                ++len;\n            else if (*s && *s != ' ')\n                len = 0;\n        }\n        return len;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item 无\n\\myenddot\n"
  },
  {
    "path": "C++/chapTree.tex",
    "content": "\\chapter{树}\n\nLeetCode 上二叉树的节点定义如下：\n\\begin{Code}\n// 树的节点\nstruct TreeNode {\n    int val;\n    TreeNode *left;\n    TreeNode *right;\n    TreeNode(int x) : val(x), left(nullptr), right(nullptr) { }\n};\n\\end{Code}\n\n\n\\section{二叉树的遍历} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n树的遍历有两类：深度优先遍历和宽度优先遍历。深度优先遍历又可分为两种：先根（次序）遍历和后根（次序）遍历。\n\n树的先根遍历是：先访问树的根结点，然后依次先根遍历根的各棵子树。树的先跟遍历的结果与对应二叉树（孩子兄弟表示法）的先序遍历的结果相同。\n\n树的后根遍历是：先依次后根遍历树根的各棵子树，然后访问根结点。树的后跟遍历的结果与对应二叉树的中序遍历的结果相同。\n\n二叉树的先根遍历有：\\textbf{先序遍历}(root->left->right)，root->right->left；后根遍历有：\\textbf{后序遍历}(left->right->root)，right->left->root；二叉树还有个一般的树没有的遍历次序，\\textbf{中序遍历}(left->root->right)。\n\n\n\\subsection{Binary Tree Preorder Traversal}\n\\label{sec:binary-tree-preorder-traversal}\n\n\n\\subsubsection{描述}\nGiven a binary tree, return the \\emph{preorder} traversal of its nodes' values.\n\nFor example:\nGiven binary tree \\code{\\{1,\\#,2,3\\}},\n\\begin{Code}\n 1\n  \\\n   2\n  /\n 3\n\\end{Code}\nreturn \\code{[1,2,3]}.\n\nNote: Recursive solution is trivial, could you do it iteratively?\n\n\n\\subsubsection{分析}\n用栈或者Morris遍历。\n\n\n\\subsubsection{栈}\n\\begin{Code}\n// LeetCode, Binary Tree Preorder Traversal\n// 使用栈，时间复杂度O(n)，空间复杂度O(n)\nclass Solution {\npublic:\n    vector<int> preorderTraversal(TreeNode *root) {\n        vector<int> result;\n        stack<const TreeNode *> s;\n        if (root != nullptr) s.push(root);\n\n        while (!s.empty()) {\n            const TreeNode *p = s.top();\n            s.pop();\n            result.push_back(p->val);\n\n            if (p->right != nullptr) s.push(p->right);\n            if (p->left != nullptr) s.push(p->left);\n        }\n        return result;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{Morris先序遍历}\n\\begin{Code}\n// LeetCode, Binary Tree Preorder Traversal\n// Morris先序遍历，时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    vector<int> preorderTraversal(TreeNode *root) {\n        vector<int> result;\n        TreeNode *cur = root, *prev = nullptr;\n\n        while (cur != nullptr) {\n            if (cur->left == nullptr) {\n                result.push_back(cur->val);\n                prev = cur; /* cur刚刚被访问过 */\n                cur = cur->right;\n            } else {\n                /* 查找前驱 */\n                TreeNode *node = cur->left;\n                while (node->right != nullptr && node->right != cur)\n                    node = node->right;\n\n                if (node->right == nullptr) { /* 还没线索化，则建立线索 */\n                    result.push_back(cur->val); /* 仅这一行的位置与中序不同 */\n                    node->right = cur;\n                    prev = cur; /* cur刚刚被访问过 */\n                    cur = cur->left;\n                } else {    /* 已经线索化，则删除线索  */\n                    node->right = nullptr;\n                    /* prev = cur; 不能有这句，cur已经被访问 */\n                    cur = cur->right;\n                }\n            }\n        }\n        return result;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Binary Tree Inorder Traversal，见 \\S \\ref{sec:binary-tree-inorder-traversal}\n\\item Binary Tree Postorder Traversal，见 \\S \\ref{sec:binary-tree-postorder-traversal}\n\\item Recover Binary Search Tree，见 \\S \\ref{sec:recover-binary-search-tree}\n\\myenddot\n\n\n\\subsection{Binary Tree Inorder Traversal}\n\\label{sec:binary-tree-inorder-traversal}\n\n\n\\subsubsection{描述}\nGiven a binary tree, return the \\emph{inorder} traversal of its nodes' values.\n\nFor example:\nGiven binary tree \\code{\\{1,\\#,2,3\\}},\n\\begin{Code}\n 1\n  \\\n   2\n  /\n 3\n\\end{Code}\nreturn \\code{[1,3,2]}.\n\nNote: Recursive solution is trivial, could you do it iteratively?\n\n\n\\subsubsection{分析}\n用栈或者Morris遍历。\n\n\n\\subsubsection{栈}\n\\begin{Code}\n// LeetCode, Binary Tree Inorder Traversal\n// 使用栈，时间复杂度O(n)，空间复杂度O(n)\nclass Solution {\npublic:\n    vector<int> inorderTraversal(TreeNode *root) {\n        vector<int> result;\n        stack<const TreeNode *> s;\n        const TreeNode *p = root;\n\n        while (!s.empty() || p != nullptr) {\n            if (p != nullptr) {\n                s.push(p);\n                p = p->left;\n            } else {\n                p = s.top();\n                s.pop();\n                result.push_back(p->val);\n                p = p->right;\n            }\n        }\n        return result;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{Morris中序遍历}\n\\begin{Code}\n// LeetCode, Binary Tree Inorder Traversal\n// Morris中序遍历，时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    vector<int> inorderTraversal(TreeNode *root) {\n        vector<int> result;\n        TreeNode *cur = root, *prev = nullptr;\n\n        while (cur != nullptr) {\n            if (cur->left == nullptr) {\n                result.push_back(cur->val);\n                prev = cur;\n                cur = cur->right;\n            } else {\n                /* 查找前驱 */\n                TreeNode *node = cur->left;\n                while (node->right != nullptr && node->right != cur)\n                    node = node->right;\n\n                if (node->right == nullptr) { /* 还没线索化，则建立线索 */\n                    node->right = cur;\n                    /* prev = cur; 不能有这句，cur还没有被访问 */\n                    cur = cur->left;\n                } else {    /* 已经线索化，则访问节点，并删除线索  */\n                    result.push_back(cur->val);\n                    node->right = nullptr;\n                    prev = cur;\n                    cur = cur->right;\n                }\n            }\n        }\n        return result;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Binary Tree Preorder Traversal，见 \\S \\ref{sec:binary-tree-preorder-traversal}\n\\item Binary Tree Postorder Traversal，见 \\S \\ref{sec:binary-tree-postorder-traversal}\n\\item Recover Binary Search Tree，见 \\S \\ref{sec:recover-binary-search-tree}\n\\myenddot\n\n\n\\subsection{Binary Tree Postorder Traversal}\n\\label{sec:binary-tree-postorder-traversal}\n\n\n\\subsubsection{描述}\nGiven a binary tree, return the \\emph{postorder} traversal of its nodes' values.\n\nFor example:\nGiven binary tree \\code{\\{1,\\#,2,3\\}},\n\\begin{Code}\n 1\n  \\\n   2\n  /\n 3\n\\end{Code}\nreturn \\code{[3,2,1]}.\n\nNote: Recursive solution is trivial, could you do it iteratively?\n\n\n\\subsubsection{分析}\n用栈或者Morris遍历。\n\n\n\\subsubsection{栈}\n\\begin{Code}\n// LeetCode, Binary Tree Postorder Traversal\n// 使用栈，时间复杂度O(n)，空间复杂度O(n)\nclass Solution {\npublic:\n    vector<int> postorderTraversal(TreeNode *root) {\n        vector<int> result;\n        stack<const TreeNode *> s;\n        /* p，正在访问的结点，q，刚刚访问过的结点*/\n        const TreeNode *p = root, *q = nullptr;\n\n        do {\n            while (p != nullptr) { /* 往左下走*/\n                s.push(p);\n                p = p->left;\n            }\n            q = nullptr;\n            while (!s.empty()) {\n                p = s.top();\n                s.pop();\n                /* 右孩子不存在或已被访问，访问之*/\n                if (p->right == q) {\n                    result.push_back(p->val);\n                    q = p; /* 保存刚访问过的结点*/\n                } else {\n                    /* 当前结点不能访问，需第二次进栈*/\n                    s.push(p);\n                    /* 先处理右子树*/\n                    p = p->right;\n                    break;\n                }\n            }\n        } while (!s.empty());\n\n        return result;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{Morris后序遍历}\n\\begin{Code}\n// LeetCode, Binary Tree Postorder Traversal\n// Morris后序遍历，时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    vector<int> postorderTraversal(TreeNode *root) {\n        vector<int> result;\n        TreeNode dummy(-1);\n        TreeNode *cur, *prev = nullptr;\n        std::function < void(const TreeNode*)> visit = \n            [&result](const TreeNode *node){\n            result.push_back(node->val); \n        };\n\n        dummy.left = root;\n        cur = &dummy;\n        while (cur != nullptr) {\n            if (cur->left == nullptr) {\n                prev = cur; /* 必须要有 */\n                cur = cur->right;\n            } else {\n                TreeNode *node = cur->left;\n                while (node->right != nullptr && node->right != cur)\n                    node = node->right;\n\n                if (node->right == nullptr) { /* 还没线索化，则建立线索 */\n                    node->right = cur;\n                    prev = cur; /* 必须要有 */\n                    cur = cur->left;\n                } else { /* 已经线索化，则访问节点，并删除线索  */\n                    visit_reverse(cur->left, prev, visit);\n                    prev->right = nullptr;\n                    prev = cur; /* 必须要有 */\n                    cur = cur->right;\n                }\n            }\n        }\n        return result;\n    }\nprivate:\n    // 逆转路径\n    static void reverse(TreeNode *from, TreeNode *to) {\n        TreeNode *x = from, *y = from->right, *z;\n        if (from == to) return;\n\n        while (x != to) {\n            z = y->right;\n            y->right = x;\n            x = y;\n            y = z;\n        }\n    }\n\n    // 访问逆转后的路径上的所有结点\n    static void visit_reverse(TreeNode* from, TreeNode *to, \n                     std::function< void(const TreeNode*) >& visit) {\n        TreeNode *p = to;\n        reverse(from, to);\n\n        while (true) {\n            visit(p);\n            if (p == from)\n                break;\n            p = p->right;\n        }\n\n        reverse(to, from);\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Binary Tree Preorder Traversal，见 \\S \\ref{sec:binary-tree-preorder-traversal}\n\\item Binary Tree Inorder Traversal，见 \\S \\ref{sec:binary-tree-inorder-traversal}\n\\item Recover Binary Search Tree，见 \\S \\ref{sec:recover-binary-search-tree}\n\\myenddot\n\n\n\\subsection{Binary Tree Level Order Traversal}\n\\label{sec:binary-tree-level-order-traversal}\n\n\n\\subsubsection{描述}\nGiven a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).\n\nFor example:\nGiven binary tree \\code{\\{3,9,20,\\#,\\#,15,7\\}},\n\\begin{Code}\n    3\n   / \\\n  9  20\n    /  \\\n   15   7\n\\end{Code}\nreturn its level order traversal as:\n\\begin{Code}\n[\n  [3],\n  [9,20],\n  [15,7]\n]\n\\end{Code}\n\n\n\\subsubsection{分析}\n无\n\n\n\\subsubsection{递归版}\n\\begin{Code}\n// LeetCode, Binary Tree Level Order Traversal\n// 递归版，时间复杂度O(n)，空间复杂度O(n)\nclass Solution {\npublic:\n    vector<vector<int> > levelOrder(TreeNode *root) {\n        vector<vector<int>> result;\n        traverse(root, 1, result);\n        return result;\n    }\n\n    void traverse(TreeNode *root, size_t level, vector<vector<int>> &result) {\n        if (!root) return;\n\n        if (level > result.size())\n            result.push_back(vector<int>());\n\n        result[level-1].push_back(root->val);\n        traverse(root->left, level+1, result);\n        traverse(root->right, level+1, result);\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{迭代版}\n\\begin{Code}\n// LeetCode, Binary Tree Level Order Traversal\n// 迭代版，时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    vector<vector<int> > levelOrder(TreeNode *root) {\n        vector<vector<int> > result;\n        queue<TreeNode*> current, next;\n        \n        if(root == nullptr) {\n            return result;\n        } else {\n            current.push(root);\n        }\n\n        while (!current.empty()) {\n            vector<int> level; // elments in one level\n            while (!current.empty()) {\n                TreeNode* node = current.front();\n                current.pop();\n                level.push_back(node->val);\n                if (node->left != nullptr) next.push(node->left);\n                if (node->right != nullptr) next.push(node->right);\n            }\n            result.push_back(level);\n            swap(next, current);\n        }\n        return result;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Binary Tree Level Order Traversal II，见 \\S \\ref{sec:binary-tree-tevel-order-traversal-ii}\n\\item Binary Tree Zigzag Level Order Traversal，见 \\S \\ref{sec:binary-tree-zigzag-level-order-traversal}\n\\myenddot\n\n\n\\subsection{Binary Tree Level Order Traversal II}\n\\label{sec:binary-tree-tevel-order-traversal-ii}\n\n\n\\subsubsection{描述}\nGiven a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).\n\nFor example:\nGiven binary tree \\code{\\{3,9,20,\\#,\\#,15,7\\}},\n\\begin{Code}\n    3\n   / \\\n  9  20\n    /  \\\n   15   7\n\\end{Code}\nreturn its bottom-up level order traversal as:\n\\begin{Code}\n[\n  [15,7]\n  [9,20],\n  [3],\n]\n\\end{Code}\n\n\n\\subsubsection{分析}\n在上一题（见\\S \\ref{sec:binary-tree-tevel-order-traversal}）的基础上，\\fn{reverse()}一下即可。\n\n\n\\subsubsection{递归版}\n\\begin{Code}\n// LeetCode, Binary Tree Level Order Traversal II\n// 递归版，时间复杂度O(n)，空间复杂度O(n)\nclass Solution {\npublic:\n    vector<vector<int> > levelOrderBottom(TreeNode *root) {\n        vector<vector<int>> result;\n        traverse(root, 1, result);\n        std::reverse(result.begin(), result.end()); // 比上一题多此一行\n        return result;\n    }\n\n    void traverse(TreeNode *root, size_t level, vector<vector<int>> &result) {\n        if (!root) return;\n\n        if (level > result.size())\n            result.push_back(vector<int>());\n\n        result[level-1].push_back(root->val);\n        traverse(root->left, level+1, result);\n        traverse(root->right, level+1, result);\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{迭代版}\n\\begin{Code}\n// LeetCode, Binary Tree Level Order Traversal II\n// 迭代版，时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    vector<vector<int> > levelOrderBottom(TreeNode *root) {\n        vector<vector<int> > result;\n        if(root == nullptr) return result;\n\n        queue<TreeNode*> current, next;\n        vector<int> level; // elments in level level\n\n        current.push(root);\n        while (!current.empty()) {\n            while (!current.empty()) {\n                TreeNode* node = current.front();\n                current.pop();\n                level.push_back(node->val);\n                if (node->left != nullptr) next.push(node->left);\n                if (node->right != nullptr) next.push(node->right);\n            }\n            result.push_back(level);\n            level.clear();\n            swap(next, current);\n        }\n        reverse(result.begin(), result.end()); // 比上一题多此一行\n        return result;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Binary Tree Level Order Traversal，见 \\S \\ref{sec:binary-tree-tevel-order-traversal}\n\\item Binary Tree Zigzag Level Order Traversal，见 \\S \\ref{sec:binary-tree-zigzag-level-order-traversal}\n\\myenddot\n\n\n\\subsection{Binary Tree Zigzag Level Order Traversal}\n\\label{sec:binary-tree-zigzag-level-order-traversal}\n\n\n\\subsubsection{描述}\nGiven a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).\n\nFor example:\nGiven binary tree \\code{{3,9,20,\\#,\\#,15,7}},\n\\begin{Code}\n    3\n   / \\\n  9  20\n    /  \\\n   15   7\n\\end{Code}\nreturn its zigzag level order traversal as:\n\\begin{Code}\n[\n  [3],\n  [20,9],\n  [15,7]\n]\n\\end{Code}\n\n\n\\subsubsection{分析}\n广度优先遍历，用一个bool记录是从左到右还是从右到左，每一层结束就翻转一下。\n\n\n\\subsubsection{递归版}\n\\begin{Code}\n// LeetCode, Binary Tree Zigzag Level Order Traversal\n// 递归版，时间复杂度O(n)，空间复杂度O(n)\nclass Solution {\npublic:\n    vector<vector<int> > zigzagLevelOrder(TreeNode *root) {\n        vector<vector<int>> result;\n        traverse(root, 1, result, true);\n        return result;\n    }\n\n    void traverse(TreeNode *root, size_t level, vector<vector<int>> &result,\n            bool left_to_right) {\n        if (!root) return;\n\n        if (level > result.size())\n            result.push_back(vector<int>());\n\n        if (left_to_right)\n            result[level-1].push_back(root->val);\n        else\n            result[level-1].insert(result[level-1].begin(), root->val);\n\n        traverse(root->left, level+1, result, !left_to_right);\n        traverse(root->right, level+1, result, !left_to_right);\n    }\n};\n\\end{Code}\n\n\\subsubsection{迭代版}\n\\begin{Code}\n// LeetCode, Binary Tree Zigzag Level Order Traversal\n// 广度优先遍历，用一个bool记录是从左到右还是从右到左，每一层结束就翻转一下。\n// 迭代版，时间复杂度O(n)，空间复杂度O(n)\nclass Solution {\npublic:\n    vector<vector<int> > zigzagLevelOrder(TreeNode *root) {\n        vector<vector<int> > result;\n        queue<TreeNode*> current, next;\n        bool left_to_right = true;\n        \n        if(root == nullptr) {\n            return result;\n        } else {\n            current.push(root);\n        }\n\n        while (!current.empty()) {\n            vector<int> level; // elments in one level\n            while (!current.empty()) {\n                TreeNode* node = current.front();\n                current.pop();\n                level.push_back(node->val);\n                if (node->left != nullptr) next.push(node->left);\n                if (node->right != nullptr) next.push(node->right);\n            }\n            if (!left_to_right) reverse(level.begin(), level.end());\n            result.push_back(level);\n            left_to_right = !left_to_right;\n            swap(next, current);\n        }\n        return result;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Binary Tree Level Order Traversal，见 \\S \\ref{sec:binary-tree-tevel-order-traversal}\n\\item Binary Tree Level Order Traversal II，见 \\S \\ref{sec:binary-tree-tevel-order-traversal-ii}\n\\myenddot\n\n\n\\subsection{Recover Binary Search Tree}\n\\label{sec:recover-binary-search-tree}\n\n\n\\subsubsection{描述}\nTwo elements of a binary search tree (BST) are swapped by mistake.\n\nRecover the tree without changing its structure.\n\nNote: A solution using $O(n)$ space is pretty straight forward. Could you devise a constant space solution?\n\n\n\\subsubsection{分析}\n$O(n)$空间的解法是，开一个指针数组，中序遍历，将节点指针依次存放到数组里，然后寻找两处逆向的位置，先从前往后找第一个逆序的位置，然后从后往前找第二个逆序的位置，交换这两个指针的值。\n\n中序遍历一般需要用到栈，空间也是$O(n)$的，如何才能不使用栈？Morris中序遍历。\n\n\n\\subsubsection{代码}\n\n\\begin{Code}\n// LeetCode, Recover Binary Search Tree\n// Morris中序遍历，时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    void recoverTree(TreeNode* root) {\n        pair<TreeNode*, TreeNode*> broken;\n        TreeNode* prev = nullptr;\n        TreeNode* cur = root;\n\n        while (cur != nullptr) {\n            if (cur->left == nullptr) {\n                detect(broken, prev, cur);\n                prev = cur;\n                cur = cur->right;\n            } else {\n                auto node = cur->left;\n\n                while (node->right != nullptr && node->right != cur)\n                    node = node->right;\n\n                if (node->right == nullptr) {\n                    node->right = cur;\n                    //prev = cur; 不能有这句！因为cur还没有被访问\n                    cur = cur->left;\n                } else {\n                    detect(broken, prev, cur);\n                    node->right = nullptr;\n                    prev = cur;\n                    cur = cur->right;\n                }\n            }\n        }\n\n        swap(broken.first->val, broken.second->val);\n    }\n\n    void detect(pair<TreeNode*, TreeNode*>& broken, TreeNode* prev,\n            TreeNode* current) {\n        if (prev != nullptr && prev->val > current->val) {\n            if (broken.first == nullptr) {\n                broken.first = prev;\n            } //不能用else，例如 {0,1}，会导致最后 swap时second为nullptr，\n              //会 Runtime Error\n            broken.second = current;\n        }\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Binary Tree Inorder Traversal，见 \\S \\ref{sec:binary-tree-inorder-traversal}\n\\myenddot\n\n\n\\subsection{Same Tree}\n\\label{sec:same-tree}\n\n\n\\subsubsection{描述}\nGiven two binary trees, write a function to check if they are equal or not.\n\nTwo binary trees are considered equal if they are structurally identical and the nodes have the same value.\n\n\n\\subsubsection{分析}\n无\n\n\n\\subsubsection{递归版}\n递归版\n\\begin{Code}\n// LeetCode, Same Tree\n// 递归版，时间复杂度O(n)，空间复杂度O(logn)\nclass Solution {\npublic:\n    bool isSameTree(TreeNode *p, TreeNode *q) {\n        if (!p && !q) return true;   // 终止条件\n        if (!p || !q) return false;  // 剪枝\n        return p->val == q->val      // 三方合并\n                && isSameTree(p->left, q->left)\n                && isSameTree(p->right, q->right);\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{迭代版}\n\\begin{Code}\n// LeetCode, Same Tree\n// 迭代版，时间复杂度O(n)，空间复杂度O(logn)\nclass Solution {\npublic:\n    bool isSameTree(TreeNode *p, TreeNode *q) {\n        stack<TreeNode*> s;\n        s.push(p);\n        s.push(q);\n\n        while(!s.empty()) {\n            p = s.top(); s.pop();\n            q = s.top(); s.pop();\n\n            if (!p && !q) continue;\n            if (!p || !q) return false;\n            if (p->val != q->val) return false;\n\n            s.push(p->left);\n            s.push(q->left);\n\n            s.push(p->right);\n            s.push(q->right);\n        }\n        return true;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Symmetric Tree，见 \\S \\ref{sec:symmetric-tree}\n\\myenddot\n\n\n\\subsection{Symmetric Tree}\n\\label{sec:symmetric-tree}\n\n\n\\subsubsection{描述}\nGiven two binary trees, write a function to check if they are equal or not.\n\nTwo binary trees are considered equal if they are structurally identical and the nodes have the same value.\n\n\n\\subsubsection{分析}\n无\n\n\n\\subsubsection{递归版}\n\\begin{Code}\n// LeetCode, Symmetric Tree\n// 递归版，时间复杂度O(n)，空间复杂度O(logn)\nclass Solution {\npublic:\n    bool isSymmetric(TreeNode *root) {\n        if (root == nullptr) return true;\n        return isSymmetric(root->left, root->right);\n    }\n    bool isSymmetric(TreeNode *p, TreeNode *q) {\n        if (p == nullptr && q == nullptr) return true;   // 终止条件\n        if (p == nullptr || q == nullptr) return false;  // 终止条件\n        return p->val == q->val      // 三方合并\n                && isSymmetric(p->left, q->right)\n                && isSymmetric(p->right, q->left);\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{迭代版}\n\\begin{Code}\n// LeetCode, Symmetric Tree\n// 迭代版，时间复杂度O(n)，空间复杂度O(logn)\nclass Solution {\npublic:\n    bool isSymmetric (TreeNode* root) {\n        if (!root) return true;\n\n        stack<TreeNode*> s;\n        s.push(root->left);\n        s.push(root->right);\n\n        while (!s.empty ()) {\n            auto p = s.top (); s.pop();\n            auto q = s.top (); s.pop();\n\n            if (!p && !q) continue;\n            if (!p || !q) return false;\n            if (p->val != q->val) return false;\n\n            s.push(p->left);\n            s.push(q->right);\n\n            s.push(p->right);\n            s.push(q->left);\n        }\n\n        return true;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Same Tree，见 \\S \\ref{sec:same-tree}\n\\myenddot\n\n\n\\subsection{Balanced Binary Tree}\n\\label{sec:balanced-binary-tree}\n\n\n\\subsubsection{描述}\nGiven a binary tree, determine if it is height-balanced.\n\nFor this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.\n\n\n\\subsubsection{分析}\n无\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Balanced Binary Tree\n// 时间复杂度O(n)，空间复杂度O(logn)\nclass Solution {\npublic:\n    bool isBalanced (TreeNode* root) {\n        return balancedHeight (root) >= 0;\n    }\n\n    /**\n     * Returns the height of `root` if `root` is a balanced tree,\n     * otherwise, returns `-1`.\n     */\n    int balancedHeight (TreeNode* root) {\n        if (root == nullptr) return 0;  // 终止条件\n\n        int left = balancedHeight (root->left);\n        int right = balancedHeight (root->right);\n\n        if (left < 0 || right < 0 || abs(left - right) > 1) return -1;  // 剪枝\n\n        return max(left, right) + 1; // 三方合并\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item 无\n\\myenddot\n\n\n\\subsection{Flatten Binary Tree to Linked List}\n\\label{sec:flatten-binary-tree-to-linked-list}\n\n\n\\subsubsection{描述}\nGiven a binary tree, flatten it to a linked list in-place.\n\nFor example, Given\n\\begin{Code}\n         1\n        / \\\n       2   5\n      / \\   \\\n     3   4   6\n\\end{Code}\n\nThe flattened tree should look like:\n\\begin{Code}\n   1\n    \\\n     2\n      \\\n       3\n        \\\n         4\n          \\\n           5\n            \\\n             6\n\\end{Code}\n\n\\subsubsection{分析}\n无\n\n\n\\subsubsection{递归版1}\n\\begin{Code}\n// LeetCode, Flatten Binary Tree to Linked List\n// 递归版1，时间复杂度O(n)，空间复杂度O(logn)\nclass Solution {\npublic:\n    void flatten(TreeNode *root) {\n        if (root == nullptr) return;  // 终止条件\n\n        flatten(root->left);\n        flatten(root->right);\n\n        if (nullptr == root->left) return;\n\n        // 三方合并，将左子树所形成的链表插入到root和root->right之间\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 = nullptr;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{递归版2}\n\\begin{Code}\n// LeetCode, Flatten Binary Tree to Linked List\n// 递归版2\n// @author 王顺达(http://weibo.com/u/1234984145)\n// 时间复杂度O(n)，空间复杂度O(logn)\nclass Solution {\npublic:\n    void flatten(TreeNode *root) {\n        flatten(root, NULL);\n    }\nprivate:\n    // 把root所代表树变成链表后，tail跟在该链表后面\n    TreeNode *flatten(TreeNode *root, TreeNode *tail) {\n        if (NULL == root) return tail;\n\n        root->right = flatten(root->left, flatten(root->right, tail));\n        root->left = NULL;\n        return root;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{迭代版}\n\\begin{Code}\n// LeetCode, Flatten Binary Tree to Linked List\n// 迭代版，时间复杂度O(n)，空间复杂度O(logn)\nclass Solution {\npublic:\n    void flatten(TreeNode* root) {\n        if (root == nullptr) return;\n\n        stack<TreeNode*> s;\n        s.push(root);\n\n        while (!s.empty()) {\n            auto p = s.top();\n            s.pop();\n\n            if (p->right)\n                s.push(p->right);\n            if (p->left)\n                s.push(p->left);\n\n            p->left = nullptr;\n            if (!s.empty())\n                p->right = s.top();\n        }\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item 无\n\\myenddot\n\n\n\\subsection{Populating Next Right Pointers in Each Node II} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:populating-next-right-pointers-in-each-node-ii}\n\n\n\\subsubsection{描述}\nFollow up for problem \"Populating Next Right Pointers in Each Node\".\n\nWhat if the given tree could be any binary tree? Would your previous solution still work?\n\nNote: You may only use constant extra space.\n\nFor example,\nGiven the following binary tree,\n\\begin{Code}\n         1\n       /  \\\n      2    3\n     / \\    \\\n    4   5    7\n\\end{Code}\n\nAfter calling your function, the tree should look like:\n\\begin{Code}\n         1 -> NULL\n       /  \\\n      2 -> 3 -> NULL\n     / \\    \\\n    4-> 5 -> 7 -> NULL\n\\end{Code}\n\n\n\\subsubsection{分析}\n要处理一个节点，可能需要最右边的兄弟节点，首先想到用广搜。但广搜不是常数空间的，本题要求常数空间。\n\n注意，这题的代码原封不动，也可以解决 Populating Next Right Pointers in Each Node I.\n\n\n\\subsubsection{递归版}\n\\begin{Code}\n// LeetCode, Populating Next Right Pointers in Each Node II\n// 时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    void connect(TreeLinkNode *root) {\n        if (root == nullptr) return;\n\n        TreeLinkNode dummy(-1);\n        for (TreeLinkNode *curr = root, *prev = &dummy; \n                curr; curr = curr->next) {\n            if (curr->left != nullptr){\n                prev->next = curr->left;\n                prev = prev->next;\n            }\n            if (curr->right != nullptr){\n                prev->next = curr->right;\n                prev = prev->next;\n            }\n        }\n        connect(dummy.next);\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{迭代版}\n\\begin{Code}\n// LeetCode, Populating Next Right Pointers in Each Node II\n// 时间复杂度O(n)，空间复杂度O(1)\nclass Solution {\npublic:\n    void connect(TreeLinkNode *root) {\n        while (root) {\n            TreeLinkNode * next = nullptr; // the first node of next level\n            TreeLinkNode * prev = nullptr; // previous node on the same level\n            for (; root; root = root->next) {\n                if (!next) next = root->left ? root->left : root->right;\n\n                if (root->left) {\n                    if (prev) prev->next = root->left;\n                    prev = root->left;\n                }\n                if (root->right) {\n                    if (prev) prev->next = root->right;\n                    prev = root->right;\n                }\n            }\n            root = next; // turn to next level\n        }\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Populating Next Right Pointers in Each Node，见 \\S \\ref{sec:populating-next-right-pointers-in-each-node}\n\\myenddot\n\n\n\\section{二叉树的构建} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\\subsection{Construct Binary Tree from Preorder and Inorder Traversal}\n\\label{sec:construct-binary-tree-from-preorder-and-inorder-traversal}\n\n\n\\subsubsection{描述}\nGiven preorder and inorder traversal of a tree, construct the binary tree.\n\nNote:\nYou may assume that duplicates do not exist in the tree.\n\n\n\\subsubsection{分析}\n无\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Construct Binary Tree from Preorder and Inorder Traversal\n// 递归，时间复杂度O(n)，空间复杂度O(\\logn)\nclass Solution {\npublic:\n    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {\n        return buildTree(begin(preorder), end(preorder),\n                begin(inorder), end(inorder));\n    }\n\n    template<typename InputIterator>\n    TreeNode* buildTree(InputIterator pre_first, InputIterator pre_last,\n            InputIterator in_first, InputIterator in_last) {\n        if (pre_first == pre_last) return nullptr;\n        if (in_first == in_last) return nullptr;\n\n        auto root = new TreeNode(*pre_first);\n\n        auto inRootPos = find(in_first, in_last, *pre_first);\n        auto leftSize = distance(in_first, inRootPos);\n\n        root->left = buildTree(next(pre_first), next(pre_first,\n                leftSize + 1), in_first, next(in_first, leftSize));\n        root->right = buildTree(next(pre_first, leftSize + 1), pre_last,\n                next(inRootPos), in_last);\n\n        return root;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Construct Binary Tree from Inorder and Postorder Traversal，见 \\S \\ref{sec:construct-binary-tree-from-inorder-and-postorder-traversal}\n\\myenddot\n\n\n\\subsection{Construct Binary Tree from Inorder and Postorder Traversal}\n\\label{sec:construct-binary-tree-from-inorder-and-postorder-traversal}\n\n\n\\subsubsection{描述}\nGiven inorder and postorder traversal of a tree, construct the binary tree.\n\nNote:\nYou may assume that duplicates do not exist in the tree.\n\n\n\\subsubsection{分析}\n无\n\n\n\\subsubsection{代码}\n\\begin{Code}\n// LeetCode, Construct Binary Tree from Inorder and Postorder Traversal\n// 递归，时间复杂度O(n)，空间复杂度O(\\logn)\nclass Solution {\npublic:\n    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {\n        return buildTree(begin(inorder), end(inorder),\n                begin(postorder), end(postorder));\n    }\n\n    template<typename BidiIt>\n    TreeNode* buildTree(BidiIt in_first, BidiIt in_last,\n            BidiIt post_first, BidiIt post_last) {\n        if (in_first ==in_last) return nullptr;\n        if (post_first == post_last) return nullptr;\n\n        const auto val = *prev(post_last);\n        TreeNode* root = new TreeNode(val);\n\n        auto in_root_pos = find(in_first, in_last, val);\n        auto left_size = distance(in_first, in_root_pos);\n        auto post_left_last = next(post_first, left_size);\n\n        root->left = buildTree(in_first, in_root_pos, post_first, post_left_last);\n        root->right = buildTree(next(in_root_pos), in_last, post_left_last,\n                prev(post_last));\n\n        return root;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Construct Binary Tree from Preorder and Inorder Traversal，见 \\S \\ref{sec:construct-binary-tree-from-preorder-and-inorder-traversal}\n\\myenddot\n\n\n\\section{二叉查找树} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\\subsection{Unique Binary Search Trees}\n\\label{sec:unique-binary-search-trees}\n\n\n\\subsubsection{描述}\nGiven $n$, how many structurally unique BST's (binary search trees) that store values $1...n$?\n\nFor example,\nGiven $n = 3$, there are a total of 5 unique BST's.\n\\begin{Code}\n   1         3     3      2      1\n    \\       /     /      / \\      \\\n     3     2     1      1   3      2\n    /     /       \\                 \\\n   2     1         2                 3\n\\end{Code}\n\n\\subsubsection{分析}\n如果把上例的顺序改一下，就可以看出规律了。\n\\begin{Code}\n 1       1           2          3       3\n  \\       \\         / \\        /       / \n   3       2       1   3      2       1\n  /         \\                /         \\\n2            3              1           2\n\\end{Code}\n\n比如，以1为根的树的个数，等于左子树的个数乘以右子树的个数，左子树是0个元素的树，右子树是2个元素的树。以2为根的树的个数，等于左子树的个数乘以右子树的个数，左子树是1个元素的树，右子树也是1个元素的树。依此类推。\n\n当数组为 $1,2,3,...,n$时，基于以下原则的构建的BST树具有唯一性：\n\\textbf{以i为根节点的树，其左子树由[1, i-1]构成， 其右子树由[i+1, n]构成。}\n\n定义$f(i)$为以$[1,i]$能产生的Unique Binary Search Tree的数目，则\n\n如果数组为空，毫无疑问，只有一种BST，即空树，$f(0)=1$。\n\n如果数组仅有一个元素{1}，只有一种BST，单个节点，$f(1)=1$。\n\n如果数组有两个元素{1,2}， 那么有如下两种可能\n\\begin{Code}\n1             2\n  \\          /\n    2      1\n\\end{Code}\n\n\\begin{eqnarray}\nf(2) &=& f(0) * f(1)   \\text{ ，1为根的情况} \\nonumber \\\\\n     &+& f(1) * f(0)   \\text{ ，2为根的情况} \\nonumber\n\\end{eqnarray}\n\n再看一看3个元素的数组，可以发现BST的取值方式如下：\n\\begin{eqnarray}\nf(3) &=& f(0) * f(2)   \\text{ ，1为根的情况} \\nonumber \\\\\n     &+& f(1) * f(1)   \\text{ ，2为根的情况} \\nonumber \\\\\n     &+& f(2) * f(0)   \\text{ ，3为根的情况} \\nonumber\n\\end{eqnarray}\n\n所以，由此观察，可以得出$f$的递推公式为\n$$\nf(i) = \\sum_{k=1}^{i} f(k-1) \\times f(i-k)\n$$\n至此，问题划归为一维动态规划。\n\n\n\\subsubsection{代码}\n\n\\begin{Code}\n// LeetCode, Unique Binary Search Trees\n// 时间复杂度O(n^2)，空间复杂度O(n)\nclass Solution {\npublic:\n    int numTrees(int n) {\n        vector<int> f(n + 1, 0);\n\n        f[0] = 1;\n        f[1] = 1;\n        for (int i = 2; i <= n; ++i) {\n            for (int k = 1; k <= i; ++k)\n                f[i] += f[k-1] * f[i - k];\n        }\n\n        return f[n];\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Unique Binary Search Trees II，见 \\S \\ref{sec:unique-binary-search-trees-ii}\n\\myenddot\n\n\n\\subsection{Unique Binary Search Trees II}\n\\label{sec:unique-binary-search-trees-ii}\n\n\n\\subsubsection{描述}\nGiven $n$, generate all structurally unique BST's (binary search trees) that store values 1...n.\n\nFor example,\nGiven $n = 3$, your program should return all 5 unique BST's shown below.\n\\begin{Code}\n   1         3     3      2      1\n    \\       /     /      / \\      \\\n     3     2     1      1   3      2\n    /     /       \\                 \\\n   2     1         2                 3\n\\end{Code}\n\n\n\\subsubsection{分析}\n见前面一题。\n\n\n\\subsubsection{代码}\n\n\\begin{Code}\n// LeetCode, Unique Binary Search Trees II\n// 时间复杂度TODO，空间复杂度TODO\nclass Solution {\npublic:\n    vector<TreeNode *> generateTrees(int n) {\n        if (n == 0) return generate(1, 0);\n        return generate(1, n);\n    }\nprivate:\n    vector<TreeNode *> generate(int start, int end) {\n        vector<TreeNode*> subTree;\n        if (start > end) {\n            subTree.push_back(nullptr);\n            return subTree;\n        }\n        for (int k = start; k <= end; k++) {\n            vector<TreeNode*> leftSubs = generate(start, k - 1);\n            vector<TreeNode*> rightSubs = generate(k + 1, end);\n            for (auto i : leftSubs) {\n                for (auto j : rightSubs) {\n                    TreeNode *node = new TreeNode(k);\n                    node->left = i;\n                    node->right = j;\n                    subTree.push_back(node);\n                }\n            }\n        }\n        return subTree;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Unique Binary Search Trees，见 \\S \\ref{sec:unique-binary-search-trees}\n\\myenddot\n\n\n\\subsection{Validate Binary Search Tree}\n\\label{sec:validate-binary-search-tree}\n\n\n\\subsubsection{描述}\nGiven a binary tree, determine if it is a valid binary search tree (BST).\n\nAssume a BST is defined as follows:\n\\begindot\n\\item The left subtree of a node contains only nodes with keys less than the node's key.\n\\item The right subtree of a node contains only nodes with keys greater than the node's key.\n\\item Both the left and right subtrees must also be binary search trees.\n\\myenddot\n\n\n\\subsubsection{分析}\n\n\n\\subsubsection{代码}\n\n\\begin{Code}\n// Validate Binary Search Tree\n// 时间复杂度O(n)，空间复杂度O(\\logn)\nclass Solution {\npublic:\n    bool isValidBST(TreeNode* root) {\n        return isValidBST(root, LONG_MIN, LONG_MAX);\n    }\n\n    bool isValidBST(TreeNode* root, long long lower, long long upper) {\n        if (root == nullptr) return true;\n\n        return root->val > lower && root->val < upper\n                && isValidBST(root->left, lower, root->val)\n                && isValidBST(root->right, root->val, upper);\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Validate Binary Search Tree，见 \\S \\ref{sec:validate-binary-search-tree}\n\\myenddot\n\n\n\\subsection{Convert Sorted Array to Binary Search Tree}\n\\label{sec:convert-sorted-array-to-binary-search-tree}\n\n\n\\subsubsection{描述}\nGiven an array where elements are sorted in ascending order, convert it to a height balanced BST.\n\n\n\\subsubsection{分析}\n二分法。\n\n\n\\subsubsection{代码}\n\n\\begin{Code}\n// LeetCode, Convert Sorted Array to Binary Search Tree\n// 分治法，时间复杂度O(n)，空间复杂度O(logn)\nclass Solution {\npublic:\n    TreeNode* sortedArrayToBST (vector<int>& num) {\n        return sortedArrayToBST(num.begin(), num.end());\n    }\n\n    template<typename RandomAccessIterator>\n    TreeNode* sortedArrayToBST (RandomAccessIterator first,\n            RandomAccessIterator last) {\n        const auto length = distance(first, last);\n\n        if (length <= 0) return nullptr;  // 终止条件\n\n        // 三方合并\n        auto mid = first + length / 2;\n        TreeNode* root = new TreeNode (*mid);\n        root->left = sortedArrayToBST(first, mid);\n        root->right = sortedArrayToBST(mid + 1, last);\n\n        return root;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Convert Sorted List to Binary Search Tree，见 \\S \\ref{sec:convert-sorted-list-to-binary-search-tree}\n\\myenddot\n\n\n\\subsection{Convert Sorted List to Binary Search Tree}\n\\label{sec:convert-sorted-list-to-binary-search-tree}\n\n\n\\subsubsection{描述}\nGiven a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.\n\n\n\\subsubsection{分析}\n这题与上一题类似，但是单链表不能随机访问，而自顶向下的二分法必须需要RandomAccessIterator，因此前面的方法不适用本题。\n\n存在一种自底向上(bottom-up)的方法，见\\myurl{http://leetcode.com/2010/11/convert-sorted-list-to-balanced-binary.html}\n\n\n\\subsubsection{分治法，自顶向下}\n分治法，类似于 Convert Sorted Array to Binary Search Tree，自顶向下，复杂度$O(n\\log n)$。\n\\begin{Code}\n// LeetCode, Convert Sorted List to Binary Search Tree\n// 分治法，类似于 Convert Sorted Array to Binary Search Tree，\n// 自顶向下，时间复杂度O(n^2)，空间复杂度O(logn)\nclass Solution {\npublic:\n    TreeNode* sortedListToBST (ListNode* head) {\n        return sortedListToBST (head, listLength (head));\n    }\n\n    TreeNode* sortedListToBST (ListNode* head, int len) {\n        if (len == 0) return nullptr;\n        if (len == 1) return new TreeNode (head->val);\n\n        TreeNode* root = new TreeNode (nth_node (head, len / 2 + 1)->val);\n        root->left = sortedListToBST (head, len / 2);\n        root->right = sortedListToBST (nth_node (head, len / 2 + 2), \n                (len - 1) / 2);\n\n        return root;\n    }\n\n    int listLength (ListNode* node) {\n        int n = 0;\n\n        while(node) {\n            ++n;\n            node = node->next;\n        }\n\n        return n;\n    }\n\n    ListNode* nth_node (ListNode* node, int n) {\n        while (--n)\n            node = node->next;\n\n        return node;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{自底向上}\n\\begin{Code}\n// LeetCode, Convert Sorted List to Binary Search Tree\n// bottom-up，时间复杂度O(n)，空间复杂度O(logn)\nclass Solution {\npublic:\n    TreeNode *sortedListToBST(ListNode *head) {\n        int len = 0;\n        ListNode *p = head;\n        while (p) {\n            len++;\n            p = p->next;\n        }\n        return sortedListToBST(head, 0, len - 1);\n    }\nprivate:\n    TreeNode* sortedListToBST(ListNode*& list, int start, int end) {\n        if (start > end) return nullptr;\n\n        int mid = start + (end - start) / 2;\n        TreeNode *leftChild = sortedListToBST(list, start, mid - 1);\n        TreeNode *parent = new TreeNode(list->val);\n        parent->left = leftChild;\n        list = list->next;\n        parent->right = sortedListToBST(list, mid + 1, end);\n        return parent;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Convert Sorted Array to Binary Search Tree，见 \\S \\ref{sec:convert-sorted-array-to-binary-search-tree}\n\\myenddot\n\n\n\\section{二叉树的递归} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n二叉树是一个递归的数据结构，因此是一个用来考察递归思维能力的绝佳数据结构。\n\n递归一定是深搜（见 \\S \\ref{sec:dfs-vs-recursion}节 “深搜与递归的区别”），由于在二叉树上，递归的味道更浓些，因此本节用“二叉树的递归”作为标题，而不是“二叉树的深搜”，尽管本节所有的算法都属于深搜。\n\n二叉树的先序、中序、后序遍历都可以看做是DFS，此外还有其他顺序的深度优先遍历，共有$3!=6$种。其他3种顺序是 \\fn{root->r->l，r->root->l, r->l->root}。\n\n\n\\subsection{Minimum Depth of Binary Tree}\n\\label{sec:minimum-depth-of-binary-tree}\n\n\n\\subsubsection{描述}\nGiven a binary tree, find its minimum depth.\n\nThe minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.\n\n\n\\subsubsection{分析}\n无\n\n\n\\subsubsection{递归版}\n\\begin{Code}\n// LeetCode, Minimum Depth of Binary Tree\n// 递归版，时间复杂度O(n)，空间复杂度O(logn)\nclass Solution {\npublic:\n    int minDepth(const TreeNode *root) {\n        return minDepth(root, false);\n    }\nprivate:\n    static int minDepth(const TreeNode *root, bool hasbrother) {\n        if (!root) return hasbrother ? INT_MAX : 0;\n\n        return 1 + min(minDepth(root->left, root->right != NULL),\n                minDepth(root->right, root->left != NULL));\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{迭代版}\n\\begin{Code}\n// LeetCode, Minimum Depth of Binary Tree\n// 迭代版，时间复杂度O(n)，空间复杂度O(logn)\nclass Solution {\npublic:\n    int minDepth(TreeNode* root) {\n        if (root == nullptr)\n            return 0;\n\n        int result = INT_MAX;\n\n        stack<pair<TreeNode*, int>> s;\n        s.push(make_pair(root, 1));\n\n        while (!s.empty()) {\n            auto node = s.top().first;\n            auto depth = s.top().second;\n            s.pop();\n\n            if (node->left == nullptr && node->right == nullptr)\n                result = min(result, depth);\n\n            if (node->left && result > depth) // 深度控制，剪枝\n                s.push(make_pair(node->left, depth + 1));\n\n            if (node->right && result > depth) // 深度控制，剪枝\n                s.push(make_pair(node->right, depth + 1));\n        }\n\n        return result;\n    }\n};\n\\end{Code}\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Maximum Depth of Binary Tree，见 \\S \\ref{sec:maximum-depth-of-binary-tree}\n\\myenddot\n\n\n\\subsection{Maximum Depth of Binary Tree}\n\\label{sec:maximum-depth-of-binary-tree}\n\n\n\\subsubsection{描述}\nGiven a binary tree, find its maximum depth.\n\nThe maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.\n\n\n\\subsubsection{分析}\n无\n\n\\subsubsection{代码}\n\n\\begin{Code}\n// LeetCode, Maximum Depth of Binary Tree\n// 时间复杂度O(n)，空间复杂度O(logn)\nclass Solution {\npublic:\n    int maxDepth(TreeNode *root) {\n        if (root == nullptr) return 0;\n\n        return max(maxDepth(root->left), maxDepth(root->right)) + 1;\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Minimum Depth of Binary Tree，见 \\S \\ref{sec:minimum-depth-of-binary-tree}\n\\myenddot\n\n\n\\subsection{Path Sum}\n\\label{sec:path-sum}\n\n\n\\subsubsection{描述}\nGiven a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.\n\nFor example:\nGiven the below binary tree and \\code{sum = 22},\n\\begin{Code}\n          5\n         / \\\n        4   8\n       /   / \\\n      11  13  4\n     /  \\      \\\n    7    2      1\n\\end{Code}\nreturn true, as there exist a root-to-leaf path \\code{5->4->11->2} which sum is 22.\n\n\n\\subsubsection{分析}\n题目只要求返回\\fn{true}或者\\fn{false}，因此不需要记录路径。\n\n由于只需要求出一个结果，因此，当左、右任意一棵子树求到了满意结果，都可以及时return。\n\n由于题目没有说节点的数据一定是正整数，必须要走到叶子节点才能判断，因此中途没法剪枝，只能进行朴素深搜。\n\n\\subsubsection{代码}\n\n\\begin{Code}\n// LeetCode, Path Sum\n// 时间复杂度O(n)，空间复杂度O(logn)\nclass Solution {\npublic:\n    bool hasPathSum(TreeNode *root, int sum) {\n        if (root == nullptr) return false;\n\n        if (root->left == nullptr && root->right == nullptr) // leaf\n            return sum == root->val;\n\n        return hasPathSum(root->left, sum - root->val)\n                || hasPathSum(root->right, sum - root->val);\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Path Sum II，见 \\S \\ref{sec:path-sum-ii}\n\\myenddot\n\n\n\\subsection{Path Sum II}\n\\label{sec:path-sum-ii}\n\n\n\\subsubsection{描述}\nGiven a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.\n\nFor example:\nGiven the below binary tree and \\code{sum = 22},\n\\begin{Code}\n          5\n         / \\\n        4   8\n       /   / \\\n      11  13  4\n     /  \\    / \\\n    7    2  5   1\n\\end{Code}\nreturn\n\\begin{Code}\n[\n   [5,4,11,2],\n   [5,8,4,5]\n]\n\\end{Code}\n\n\n\\subsubsection{分析}\n跟上一题相比，本题是求路径本身。且要求出所有结果，左子树求到了满意结果，不能return，要接着求右子树。\n\n\\subsubsection{代码}\n\n\\begin{Code}\n// LeetCode, Path Sum II\n// 时间复杂度O(n)，空间复杂度O(logn)\nclass Solution {\npublic:\n    vector<vector<int> > pathSum(TreeNode *root, int sum) {\n        vector<vector<int> > result;\n        vector<int> cur; // 中间结果\n        pathSum(root, sum, cur, result);\n        return result;\n    }\nprivate:\n    void pathSum(TreeNode *root, int gap, vector<int> &cur,\n            vector<vector<int> > &result) {\n        if (root == nullptr) return;\n\n        cur.push_back(root->val);\n\n        if (root->left == nullptr && root->right == nullptr) { // leaf\n            if (gap == root->val)\n                result.push_back(cur);\n        }\n        pathSum(root->left, gap - root->val, cur, result);\n        pathSum(root->right, gap - root->val, cur, result);\n\n        cur.pop_back();\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Path Sum，见 \\S \\ref{sec:path-sum}\n\\myenddot\n\n\n\\subsection{Binary Tree Maximum Path Sum}\n\\label{sec:binary-tree-maximum-path-sum}\n\n\n\\subsubsection{描述}\nGiven a binary tree, find the maximum path sum.\n\nThe path may start and end at any node in the tree.\nFor example:\nGiven the below binary tree,\n\\begin{Code}\n  1\n / \\\n2   3\n\\end{Code}\nReturn $6$.\n\n\n\\subsubsection{分析}\n这题很难，路径可以从任意节点开始，到任意节点结束。\n\n可以利用“最大连续子序列和”问题的思路，见第\\S \\ref{sec:maximum-subarray}节。如果说Array只有一个方向的话，那么Binary Tree其实只是左、右两个方向而已，我们需要比较两个方向上的值。\n\n不过，Array可以从头到尾遍历，那么Binary Tree怎么办呢，我们可以采用Binary Tree最常用的dfs来进行遍历。先算出左右子树的结果L和R，如果L大于0，那么对后续结果是有利的，我们加上L，如果R大于0，对后续结果也是有利的，继续加上R。\n\n\\subsubsection{代码}\n\n\\begin{Code}\n// LeetCode, Binary Tree Maximum Path Sum\n// 时间复杂度O(n)，空间复杂度O(logn)\nclass Solution {\npublic:\n    int maxPathSum(TreeNode *root) {\n        max_sum = INT_MIN;\n        dfs(root);\n        return max_sum;\n    }\nprivate:\n    int max_sum;\n    int dfs(const TreeNode *root) {\n        if (root == nullptr) return 0;\n        int l = dfs(root->left);\n        int r = dfs(root->right);\n        int sum = root->val;\n        if (l > 0) sum += l;\n        if (r > 0) sum += r;\n        max_sum = max(max_sum, sum);\n        return max(r, l) > 0 ? max(r, l) + root->val : root->val;\n    }\n};\n\\end{Code}\n\n注意，最后return的时候，只返回一个方向上的值，为什么？这是因为在递归中，只能向父节点返回，不可能存在L->root->R的路径，只可能是L->root或R->root。\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Maximum Subarray，见 \\S \\ref{sec:maximum-subarray}\n\\myenddot\n\n\n\\subsection{Populating Next Right Pointers in Each Node} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:populating-next-right-pointers-in-each-node}\n\n\n\\subsubsection{描述}\nGiven a binary tree\n\\begin{Code}\nstruct TreeLinkNode {\n   int val;\n   TreeLinkNode *left, *right, *next;\n   TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}\n};\n\\end{Code}\n\nPopulate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to \\fn{NULL}.\n\nInitially, all next pointers are set to \\fn{NULL}.\n\nNote:\n\\begindot\n\\item You may only use constant extra space.\n\\item 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\\myenddot\n\nFor example,\nGiven the following perfect binary tree,\n\\begin{Code}\n         1\n       /  \\\n      2    3\n     / \\  / \\\n    4  5  6  7\n\\end{Code}\n\nAfter calling your function, the tree should look like:\n\\begin{Code}\n         1 -> NULL\n       /  \\\n      2 -> 3 -> NULL\n     / \\  / \\\n    4->5->6->7 -> NULL\n\\end{Code}\n\n\n\\subsubsection{分析}\n无\n\n\\subsubsection{代码}\n\n\\begin{Code}\n// LeetCode, Populating Next Right Pointers in Each Node\n// 时间复杂度O(n)，空间复杂度O(logn)\nclass Solution {\npublic:\n    void connect(TreeLinkNode *root) {\n        connect(root, NULL);\n    }\nprivate:\n    void connect(TreeLinkNode *root, TreeLinkNode *sibling) {\n        if (root == nullptr)\n            return;\n        else\n            root->next = sibling;\n\n        connect(root->left, root->right);\n        if (sibling)\n            connect(root->right, sibling->left);\n        else\n            connect(root->right, nullptr);\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item Populating Next Right Pointers in Each Node II，见 \\S \\ref{sec:populating-next-right-pointers-in-each-node-ii}\n\\myenddot\n\n\n\\subsection{Sum Root to Leaf Numbers} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:sum-root-to-leaf-numbers}\n\n\n\\subsubsection{描述}\nGiven a binary tree containing digits from \\fn{0-9} only, each root-to-leaf path could represent a number.\n\nAn example is the root-to-leaf path \\fn{1->2->3} which represents the number \\fn{123}.\n\nFind the total sum of all root-to-leaf numbers.\n\nFor example,\n\\begin{Code}\n    1\n   / \\\n  2   3\n\\end{Code}\n\nThe root-to-leaf path \\fn{1->2} represents the number \\fn{12}.\nThe root-to-leaf path \\fn{1->3} represents the number \\fn{13}.\n\nReturn the sum = \\fn{12 + 13 = 25}.\n\n\n\\subsubsection{分析}\n无\n\n\\subsubsection{代码}\n\n\\begin{Code}\n// LeetCode, Decode Ways\n// 时间复杂度O(n)，空间复杂度O(logn)\nclass Solution {\npublic:\n    int sumNumbers(TreeNode *root) {\n        return dfs(root, 0);\n    }\nprivate:\n    int dfs(TreeNode *root, int sum) {\n        if (root == nullptr) return 0;\n        if (root->left == nullptr && root->right == nullptr)\n            return sum * 10 + root->val;\n\n        return dfs(root->left, sum * 10 + root->val) +\n                dfs(root->right, sum * 10 + root->val);\n    }\n};\n\\end{Code}\n\n\n\\subsubsection{相关题目}\n\\begindot\n\\item 无\n\\myenddot\n"
  },
  {
    "path": "C++/chapTrick.tex",
    "content": "\\chapter{编程技巧}\n\n在判断两个浮点数a和b是否相等时，不要用\\fn{a==b}，应该判断二者之差的绝对值\\fn{fabs(a-b)}是否小于某个阈值，例如\\fn{1e-9}。\n\n判断一个整数是否是为奇数，用\\fn{x \\% 2 != 0}，不要用\\fn{x \\% 2 == 1}，因为x可能是负数。\n\n用\\fn{char}的值作为数组下标（例如，统计字符串中每个字符出现的次数），要考虑到\\fn{char}可能是负数。有的人考虑到了，先强制转型为\\fn{unsigned int}再用作下标，这仍然是错的。正确的做法是，先强制转型为\\fn{unsigned char}，再用作下标。这涉及C++整型提升的规则，就不详述了。\n\n以下是关于STL使用技巧的，很多条款来自《Effective STL》这本书。\n\n\\subsubsection{vector和string优先于动态分配的数组}\n\n首先，在性能上，由于\\fn{vector}能够保证连续内存，因此一旦分配了后，它的性能跟原始数组相当；\n\n其次，如果用new，意味着你要确保后面进行了delete，一旦忘记了，就会出现BUG，且这样需要都写一行delete，代码不够短；\n\n再次，声明多维数组的话，只能一个一个new，例如：\n\\begin{Code}\nint** ary = new int*[row_num];\nfor(int i = 0; i < row_num; ++i)\n    ary[i] = new int[col_num];\n\\end{Code}\n用vector的话一行代码搞定，\n\\begin{Code}\nvector<vector<int> > ary(row_num, vector<int>(col_num, 0));\n\\end{Code}\n\n\\subsubsection{使用reserve来避免不必要的重新分配}\n"
  },
  {
    "path": "C++/format.cls",
    "content": "\\usepackage[centering,paperwidth=180mm,paperheight=230mm,%\nbody={390pt,530pt},marginparsep=10pt,marginpar=50pt]{geometry}\n\\usepackage{color}\n\\usepackage{enumitem}\n\\usepackage{fancyvrb}\n\\usepackage[bottom,perpage,symbol*]{footmisc}\n\\usepackage{graphicx}\n\\usepackage[hidelinks]{hyperref}\n\\usepackage{makeidx}\n\\usepackage[toc]{multitoc}\n\\usepackage{pifont}\n\\usepackage{underscore}\n\\usepackage{amsmath}\n\n\\DefineFNsymbols*{chinese}{{\\ding{172}}{\\ding{173}}{\\ding{174}}{\\ding{175}}%\n{\\ding{176}}{\\ding{177}}{\\ding{178}}{\\ding{179}}{\\ding{180}}{\\ding{181}}}\n\\setfnsymbol{chinese}\n\n\\hypersetup{bookmarksnumbered=true,bookmarksdepth=2}\n\n\\CTEXsetup[number={\\thechapter}]{chapter}\n\\CTEXsetup[format+={\\raggedleft}]{chapter}\n\\CTEXsetup[beforeskip={10pt}]{chapter}\n\\CTEXsetup[afterskip={30pt}]{chapter}\n\\def\\CTEX@chapter@aftername{\\par} % \\CTEXsetup[aftername={\\par}]{chapter}\n\\CTEXsetup[format+={\\raggedright}]{section}\n\\CTEXsetup[beforeskip={-3.0ex plus -1ex minus -.2ex}]{section}\n\\CTEXsetup[afterskip={2.3ex plus .2ex minus 0.2ex}]{section}\n\n\\renewcommand \\thefigure{\\thechapter-\\arabic{figure}}\n\\renewcommand \\thetable{\\thechapter-\\arabic{table}}\n\n\\newcommand\\figcaption[1]{\\def\\@captype{figure}\\caption{#1}}\n\\newcommand\\tabcaption[1]{\\def\\@captype{table}\\caption{#1}}\n\n\\long\\def\\@caption#1[#2]#3{%\n  \\addcontentsline{\\csname ext@#1\\endcsname}{#1}%\n    {\\protect\\numberline{\\csname fnum@#1\\endcsname}{ \\ignorespaces #2}}% change \"the\" to \"fnum@\"\n    \\normalsize\n    \\@makecaption{\\csname fnum@#1\\endcsname}{\\ignorespaces #3}}\n\n\\long\\def\\@makecaption#1#2{%\n  \\vskip\\abovecaptionskip\n  \\sbox\\@tempboxa{#1\\quad#2}%\n  \\ifdim \\wd\\@tempboxa >\\hsize\n    #1\\quad#2\\par\n  \\else\n    \\global \\@minipagefalse\n    \\hb@xt@\\hsize{\\hfil\\box\\@tempboxa\\hfil}%\n  \\fi\n  \\vskip\\belowcaptionskip}\n\n\\setlength\\abovecaptionskip{0pt}\n  \n\\setmainfont{Times New Roman}\n%\\setmainfont{Linux Libertine}\n%\\setmainfont{TeX Gyre Pagella}\n\\newfontfamily\\urlfont{PT Sans Narrow}\n%\\setmonofont[AutoFakeBold=1.6,AutoFakeSlant=0.17,Mapping=tex-text-tt]{Inconsolata}\n\\setCJKfamilyfont{zhyou}{YouYuan}\n\n\\newcommand{\\fn}[1]{\\texttt{#1}}\n\\newcommand{\\sfn}[1]{\\texttt{\\small #1}}\n\\newcommand{\\kw}[1]{\\textsf{#1}}\n\\newcommand{\\myurl}[1]{{\\urlfont #1}}\n\\newcommand{\\mpar}[1]{\\marginpar[\\hfill\\kaishu #1]{\\kaishu #1}}\n\\newcommand{\\mn}[1]{\\texttt{\\bs #1}}\n\\renewcommand{\\today}{\\the\\year-\\the\\month-\\the\\day}\n\\newcommand\\bs{\\textbackslash}\n\\newcommand{\\code}[1]{\\small{\\fontspec{Latin Modern Mono} #1}}\n\n\\newcommand\\begindot{\\begin{itemize}\n[itemsep=2pt plus 2pt minus 2pt,%\ntopsep=3pt plus 2pt minus 2pt,%\nparsep=0pt plus 2pt minus 2pt]}\n\\newcommand\\myenddot{\\end{itemize}}\n\n\\newcommand\\beginnum{\\begin{enumerate}\n[itemsep=2pt plus 2pt minus 2pt,%\ntopsep=3pt plus 2pt minus 2pt,%\nparsep=0pt plus 2pt minus 2pt]}\n\\newcommand\\myendnum{\\end{enumerate}}\n\n\\DefineVerbatimEnvironment%\n  {Code}{Verbatim}\n  {fontsize=\\small,baselinestretch=0.9,xleftmargin=3mm}\n\n\\raggedbottom\n%\\setlength{\\parskip}{1ex plus .5ex minus .5ex}\n\n\\input{verbatim.cls}\n\\DefineVerbatimEnvironment%\n  {Codex}{Verbatim}\n  {fontsize=\\small,baselinestretch=0.9,xleftmargin=3mm,%\n  frame=lines,labelposition=all,framesep=5pt}\n\n\\DefineVerbatimEnvironment%\n  {Code}{Verbatim}\n  {fontsize=\\small,baselinestretch=0.9,xleftmargin=3mm}\n\n\\makeindex\n"
  },
  {
    "path": "C++/leetcode-cpp.tex",
    "content": "\\documentclass[10pt,adobefonts,fancyhdr,hyperref,UTF8]{ctexbook}\n\n\\usepackage{multirow}\n% for \\soul 删除线\n\\usepackage{ulem}\n% 表头斜线\n\\usepackage{diagbox}\n\n\\makeatletter\n\\input{format.cls}\n\\makeatother\n\n\\begin{document}\n\\sloppy\n\\newcommand\\BookTitle{LeetCode题解}\n\\pagestyle{fancy}\n\\fancyhf{}\n\\fancyhead[RE]{\\normalfont\\small\\rmfamily\\nouppercase{\\leftmark}}\n\\fancyhead[LO]{\\normalfont\\small\\rmfamily\\nouppercase{\\rightmark}}\n\\fancyhead[LE,RO]{\\thepage}\n%\\fancyfoot[LE,LO]{\\small\\normalfont\\youyuan\\BookTitle}\n%\\fancyfoot[RE,RO]{\\textsf{\\small \\color{blue} https://github.com/soulmachine/leetcode}}\n\n\\makeatletter\n\\@openrightfalse\n\\makeatother\n\n\\frontmatter % 开始前言目录，页码用罗马数字\n\n\\include{title}\n\n\\tableofcontents\n\n\\mainmatter % 开始正文，页码用阿拉伯数字\n\n\\graphicspath{{images/}}\n\n\\include{chapTrick}\n\\include{chapLinearList}\n\\include{chapString}\n\\include{chapStackAndQueue}\n\\include{chapTree}\n\\include{chapSorting}\n\\include{chapSearching}\n\\include{chapBruteforce}\n\\include{chapBFS}\n\\include{chapDFS}\n\\include{chapDivideAndConquer}\n\\include{chapGreedy}\n\\include{chapDynamicProgramming}\n\\include{chapGraph}\n\\include{chapImplement}\n\n\\appendix % 开始附录，章用字母编号\n\\printindex\n\n\\end{document}\n"
  },
  {
    "path": "C++/title.tex",
    "content": "\\thispagestyle{plain}\n\\begin{center}\n  {\\LARGE\\textbf{\\BookTitle}}\n\n  \\vspace{1em}\n  {\\large 灵魂机器 (soulmachine@gmail.com)}\n\n  \\vspace{1ex}\n  \\myurl{https://github.com/soulmachine/leetcode}\n  \n  \\vspace{1ex}\n  最后更新 \\today\n  \n  \\vspace{1em}\n  \\textbf{\\large 版权声明}\n\\end{center}\n\\noindent 本作品采用“Creative Commons 署名-非商业性使用-相同方式共享 3.0 Unported许可协议 \n(cc by-nc-sa)”进行许可。\n\\texttt{\\small http://creativecommons.org/licenses/by-nc-sa/3.0/}\n\n\\vspace{1em}\n\\input{abstract}"
  },
  {
    "path": "C++/verbatim.cls",
    "content": "\\def\\FV@SetLineWidth{%\n  \\if@FV@ResetMargins\\else\n    \\advance\\leftmargin\\@totalleftmargin\n  \\fi\n  \\advance\\leftmargin\\FV@XLeftMargin\\relax\n  \\advance\\rightmargin\\FV@XRightMargin\\relax\n  \\linewidth\\hsize\n  %\\advance\\linewidth-\\leftmargin\n  %\\advance\\linewidth-\\rightmargin\n  \\hfuzz\\FancyVerbHFuzz\\relax}\n\n\n\\def\\FV@SingleFrameLine#1{%\n%% DG/SR modification end\n  \\hbox to\\z@{%\n    %\\kern\\leftmargin\n%% DG/SR modification begin - Jun. 22, 1998\n    \\ifnum#1=\\z@\n      \\let\\FV@Label\\FV@LabelBegin\n    \\else\n      \\let\\FV@Label\\FV@LabelEnd\n    \\fi\n    \\ifx\\FV@Label\\relax\n%% DG/SR modification end\n      \\FancyVerbRuleColor{\\vrule \\@width\\linewidth \\@height\\FV@FrameRule}%\n%% DG/SR modification begin - Jun. 22, 1998\n    \\else\n      \\ifnum#1=\\z@\n        \\setbox\\z@\\hbox{\\strut\\enspace\\urlfont\\FV@LabelBegin\\strut}%\n      \\else\n        \\setbox\\z@\\hbox{\\strut\\enspace\\urlfont\\FV@LabelEnd\\strut}%\n      \\fi\n      \\@tempdimb=\\dp\\z@\n      \\advance\\@tempdimb -.5\\ht\\z@\n      \\@tempdimc=\\linewidth\n      \\advance\\@tempdimc -\\wd\\z@\n      %\\divide\\@tempdimc\\tw@\n      \\ifnum#1=\\z@              % Top line\n        \\ifx\\FV@LabelPositionTopLine\\relax\n          \\FancyVerbRuleColor{\\vrule \\@width\\linewidth \\@height\\FV@FrameRule}%\n        \\else\n          \\FV@FrameLineWithLabel\n        \\fi\n      \\else                     % Bottom line\n        \\ifx\\FV@LabelPositionBottomLine\\relax\n          \\FancyVerbRuleColor{\\vrule \\@width\\linewidth \\@height\\FV@FrameRule}%\n        \\else\n          \\FV@FrameLineWithLabel\n        \\fi\n      \\fi\n    \\fi\n%% DG/SR modification end\n    \\hss}}\n\n\n%% DG/SR modification begin - May. 19, 1998\n\\def\\FV@FrameLineWithLabel{%\n  \\ht\\z@\\@tempdimb\\dp\\z@\\@tempdimb%\n  \\FancyVerbRuleColor{%\n    \\raise 0.5ex\\hbox{\\vrule \\@width\\@tempdimc \\@height\\FV@FrameRule}%\n    \\raise\\@tempdimb\\box\\z@}}\n%% DG/SR modification end\n\n\n\\def\\FV@EndListFrame@Lines{%\n  \\begingroup\n    %\\vskip 0.5ex\n    \\baselineskip\\z@skip\n    \\kern\\FV@FrameSep\\relax\n%% DG/SR modification begin - May. 19, 1998\n%%    \\FV@SingleFrameLine\n    \\FV@SingleFrameLine{\\@ne}%\n%% DG/SR modification end\n  \\endgroup}\n\n\\newskip\\mytopsep\n\\setlength{\\mytopsep}{4pt plus 2pt minus 3pt}\n\n\\def\\FV@ListVSpace{%\n  \\@topsepadd\\mytopsep\n  \\if@noparlist\\advance\\@topsepadd\\partopsep\\fi\n  \\if@inlabel\n    \\vskip\\parskip\n  \\else\n    \\if@nobreak\n      \\vskip\\parskip\n      \\clubpenalty\\@M\n    \\else\n      \\addpenalty\\@beginparpenalty\n      \\@topsep\\@topsepadd\n      \\advance\\@topsep\\parskip\n      \\addvspace\\@topsep\n    \\fi\n  \\fi\n  %\\showthe \\@topsepadd\n  %\\showthe \\topsep\n  %\\showthe \\partopsep\n  %\\showthe \\parskip\n  \\global\\@nobreakfalse\n  \\global\\@inlabelfalse\n  \\global\\@minipagefalse\n  \\global\\@newlistfalse}\n\n\\def\\FV@EndList{%\n  \\FV@ListProcessLastLine\n  \\FV@EndListFrame\n  %\\showthe \\@topsepadd\n  \\@endparenv\n  \\endgroup\n  \\@endpetrue}\n\n\\def\\theFancyVerbLine{\\sffamily\\scriptsize\\arabic{FancyVerbLine}}\n"
  },
  {
    "path": "Java/README.md",
    "content": "#Java版\n-----------------\n\n## 编译\n\n    docker pull soulmachine/texlive\n    docker run -it --rm -v $(pwd):/data -w /data soulmachine/texlive-full xelatex -synctex=1 -interaction=nonstopmode leetcode-java.tex\n"
  },
  {
    "path": "LICENSE",
    "content": "Copyright (c) 2013, soulmachine and The Contributors\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n  * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n\n  * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n\n  * Neither the name of the soulmachine nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
  },
  {
    "path": "README.md",
    "content": "# LeetCode题解\n\n## 在线阅读\n\n<https://algorithm-essentials.soulmachine.me/>\n\n## PDF下载\n\n<a href=\"https://github.com/soulmachine/leetcode/raw/master/C%2B%2B/leetcode-cpp.pdf\">LeetCode题解(C++版).pdf</a>\n\nC++ 文件夹下是C++版，内容一模一样，代码是用C++写的。\n\nJava 文件夹下是Java版，目前正在编写中，由于拖延症，不知道猴年马月能完成。\n\n## 如何编译PDF\n\n### 命令行编译\n\n```bash\ndocker run -it --rm -v $(pwd)/C++:/project -w /project soulmachine/texlive xelatex -interaction=nonstopmode leetcode-cpp.tex\n```\n\n### vscode下编译\n\n本项目已经配置好了vscode devcontainer, 可以在 Windows, Linux 和 macOS 三大平台上编译。\n\n用 vscode 打开本项目，选择右下角弹出的 `\"Reopen in Container\"`，就会在容器中打开本项目，该容器安装了 Tex Live 2022 以及所需要的10个字体。\n\n点击vscode左下角的齿轮图标，选择 `Command Palette`，输入`tasks`, 选择 `Run Task`， 选择 `leetcode-C++`，即可启动编译。\n\n## LaTeX模板\n\n本书使用的是陈硕开源的[模板](https://github.com/chenshuo/typeset)。这个模板制作精良，感谢陈硕 :)\n\n这个LaTex模板总共使用了10个字体，下载地址 <https://pan.baidu.com/s/1eRFJXnW> 。有的字体Windows自带了，有的字体Ubuntu自带了，但都不全，还是一次性安装完所有字体比较方便。\n\n也可以参考 [Dockerfile](https://github.com/soulmachine/docker-images/blob/master/texlive/Dockerfile) 去学习如何安装所有字体。\n\n## 贡献代码\n\n欢迎给本书添加内容或纠正错误，在自己本地编译成PDF，预览没问题后，就可以发pull request过来了。\n"
  }
]