Showing preview only (358K chars total). Download the full file or copy to clipboard to get everything.
Repository: soulmachine/leetcode
Branch: master
Commit: a12593e0d6da
Files: 28
Total size: 345.6 KB
Directory structure:
gitextract_i3l5z3yw/
├── .devcontainer/
│ └── devcontainer.json
├── .gitignore
├── .vscode/
│ └── tasks.json
├── C++/
│ ├── README.md
│ ├── abstract.tex
│ ├── chapBFS.tex
│ ├── chapBruteforce.tex
│ ├── chapDFS.tex
│ ├── chapDivideAndConquer.tex
│ ├── chapDynamicProgramming.tex
│ ├── chapGraph.tex
│ ├── chapGreedy.tex
│ ├── chapImplement.tex
│ ├── chapLinearList.tex
│ ├── chapSearching.tex
│ ├── chapSorting.tex
│ ├── chapStackAndQueue.tex
│ ├── chapString.tex
│ ├── chapTree.tex
│ ├── chapTrick.tex
│ ├── format.cls
│ ├── leetcode-cpp.tex
│ ├── tex-text-tt.tec
│ ├── title.tex
│ └── verbatim.cls
├── Java/
│ └── README.md
├── LICENSE
└── README.md
================================================
FILE CONTENTS
================================================
================================================
FILE: .devcontainer/devcontainer.json
================================================
{
"name": "TeX Live",
"image": "soulmachine/texlive:latest",
"extensions": [
"James-Yu.latex-workshop"
]
}
================================================
FILE: .gitignore
================================================
*.log
*.toc
*.aux
*.idx
*.out
*.synctex.gz
================================================
FILE: .vscode/tasks.json
================================================
{
"version": "2.0.0",
"tasks": [
{
"label": "lettcode-C++",
"type": "shell",
"command": "xelatex",
"args": [
"-synctex=1",
"-interaction=nonstopmode",
"leetcode-cpp.tex"
],
"options": {
"cwd": "${workspaceFolder}/C++/"
}
},
{
"label": "lettcode-Java",
"type": "shell",
"command": "xelatex",
"args": [
"-synctex=1",
"-interaction=nonstopmode",
"leetcode-java.tex"
],
"options": {
"cwd": "${workspaceFolder}/Java/"
}
}
]
}
================================================
FILE: C++/README.md
================================================
# C++版
## 编译
```bash
docker run -it --rm -v $(pwd):/project -w /project soulmachine/texlive xelatex -interaction=nonstopmode leetcode-cpp.tex
````
================================================
FILE: C++/abstract.tex
================================================
\subsubsection{内容简介}
本书的目标读者是准备去北美找工作的码农,也适用于在国内找工作的码农,以及刚接触ACM算法竞赛的新手。
本书包含了 LeetCode Online Judge(\myurl{http://leetcode.com/onlinejudge})所有题目的答案,
所有代码经过精心编写,编码规范良好,适合读者反复揣摩,模仿,甚至在纸上默写。
全书的代码,使用C++ 11的编写,并在 LeetCode Online Judge 上测试通过。本书中的代码规范,跟在公司中的工程规范略有不同,为了使代码短(方便迅速实现):
\begindot
\item 所有代码都是单一文件。这是因为一般OJ网站,提交代码的时候只有一个文本框,如果还是
按照标准做法,比如分为头文件.h和源代码.cpp,无法在网站上提交;
\item Shorter is better。能递归则一定不用栈;能用STL则一定不自己实现。
\item 不提倡防御式编程。不需要检查malloc()/new 返回的指针是否为nullptr;不需要检查内部函数入口参数的有效性。
\myenddot
本手册假定读者已经学过《数据结构》\footnote{《数据结构》,严蔚敏等著,清华大学出版社,
\myurl{http://book.douban.com/subject/2024655/}},
《算法》\footnote{《Algorithms》,Robert Sedgewick, Addison-Wesley Professional, \myurl{http://book.douban.com/subject/4854123/}}
这两门课,熟练掌握C++或Java。
\subsubsection{GitHub地址}
本书是开源的,GitHub地址:\myurl{https://github.com/soulmachine/leetcode}
\subsubsection{北美求职微博群}
我和我的小伙伴们在这里:\myurl{http://q.weibo.com/1312378}
================================================
FILE: C++/chapBFS.tex
================================================
\chapter{广度优先搜索}
当题目看不出任何规律,既不能用分治,贪心,也不能用动规时,这时候万能方法——搜索,
就派上用场了。搜索分为广搜和深搜,广搜里面又有普通广搜,双向广搜,A*搜索等。
深搜里面又有普通深搜,回溯法等。
广搜和深搜非常类似(除了在扩展节点这部分不一样),二者有相同的框架,如何表示状态?
如何扩展状态?如何判重?尤其是判重,解决了这个问题,基本上整个问题就解决了。
\section{Word Ladder} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:word-ladder}
\subsubsection{描述}
Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:
\begindot
\item Only one letter can be changed at a time
\item Each intermediate word must exist in the dictionary
\myenddot
For example, Given:
\begin{Code}
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
\end{Code}
As one shortest transformation is \code{"hit" -> "hot" -> "dot" -> "dog" -> "cog"}, return its length $5$.
Note:
\begindot
\item Return 0 if there is no such transformation sequence.
\item All words have the same length.
\item All words contain only lowercase alphabetic characters.
\myenddot
\subsubsection{分析}
求最短路径,用广搜。
\subsubsection{单队列}
\begin{Code}
//LeetCode, Word Ladder
// 时间复杂度O(n),空间复杂度O(n)
struct state_t {
string word;
int level;
state_t() { word = ""; level = 0; }
state_t(const string& word, int level) {
this->word = word;
this->level = level;
}
bool operator==(const state_t &other) const {
return this->word == other.word;
}
};
namespace std {
template<> struct hash<state_t> {
public:
size_t operator()(const state_t& s) const {
return str_hash(s.word);
}
private:
std::hash<std::string> str_hash;
};
}
class Solution {
public:
int ladderLength(const string& start, const string &end,
const unordered_set<string> &dict) {
queue<state_t> q;
unordered_set<state_t> visited; // 判重
auto state_is_valid = [&](const state_t& s) {
return dict.find(s.word) != dict.end() || s.word == end;
};
auto state_is_target = [&](const state_t &s) {return s.word == end; };
auto state_extend = [&](const state_t &s) {
unordered_set<state_t> result;
for (size_t i = 0; i < s.word.size(); ++i) {
state_t new_state(s.word, s.level + 1);
for (char c = 'a'; c <= 'z'; c++) {
// 防止同字母替换
if (c == new_state.word[i]) continue;
swap(c, new_state.word[i]);
if (state_is_valid(new_state) &&
visited.find(new_state) == visited.end()) {
result.insert(new_state);
}
swap(c, new_state.word[i]); // 恢复该单词
}
}
return result;
};
state_t start_state(start, 0);
q.push(start_state);
visited.insert(start_state);
while (!q.empty()) {
// 千万不能用 const auto&,pop() 会删除元素,
// 引用就变成了悬空引用
const auto state = q.front();
q.pop();
if (state_is_target(state)) {
return state.level + 1;
}
const auto& new_states = state_extend(state);
for (const auto& new_state : new_states) {
q.push(new_state);
visited.insert(new_state);
}
}
return 0;
}
};
\end{Code}
\subsubsection{双队列}
\begin{Code}
//LeetCode, Word Ladder
// 时间复杂度O(n),空间复杂度O(n)
class Solution {
public:
int ladderLength(const string& start, const string &end,
const unordered_set<string> &dict) {
queue<string> current, next; // 当前层,下一层
unordered_set<string> visited; // 判重
int level = -1; // 层次
auto state_is_valid = [&](const string& s) {
return dict.find(s) != dict.end() || s == end;
};
auto state_is_target = [&](const string &s) {return s == end;};
auto state_extend = [&](const string &s) {
unordered_set<string> result;
for (size_t i = 0; i < s.size(); ++i) {
string new_word(s);
for (char c = 'a'; c <= 'z'; c++) {
// 防止同字母替换
if (c == new_word[i]) continue;
swap(c, new_word[i]);
if (state_is_valid(new_word) &&
visited.find(new_word) == visited.end()) {
result.insert(new_word);
}
swap(c, new_word[i]); // 恢复该单词
}
}
return result;
};
current.push(start);
visited.insert(start);
while (!current.empty()) {
++level;
while (!current.empty()) {
// 千万不能用 const auto&,pop() 会删除元素,
// 引用就变成了悬空引用
const auto state = current.front();
current.pop();
if (state_is_target(state)) {
return level + 1;
}
const auto& new_states = state_extend(state);
for (const auto& new_state : new_states) {
next.push(new_state);
visited.insert(new_state);
}
}
swap(next, current);
}
return 0;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Word Ladder II,见 \S \ref{sec:word-ladder-ii}
\myenddot
\section{Word Ladder II} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:word-ladder-ii}
\subsubsection{描述}
Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from start to end, such that:
\begindot
\item Only one letter can be changed at a time
\item Each intermediate word must exist in the dictionary
\myenddot
For example, Given:
\begin{Code}
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
\end{Code}
Return
\begin{Code}
[
["hit","hot","dot","dog","cog"],
["hit","hot","lot","log","cog"]
]
\end{Code}
Note:
\begindot
\item All words have the same length.
\item All words contain only lowercase alphabetic characters.
\myenddot
\subsubsection{分析}
跟 Word Ladder比,这题是求路径本身,不是路径长度,也是BFS,略微麻烦点。
求一条路径和求所有路径有很大的不同,求一条路径,每个状态节点只需要记录一个前驱即可;求所有路径时,有的状态节点可能有多个父节点,即要记录多个前驱。
如果当前路径长度已经超过当前最短路径长度,可以中止对该路径的处理,因为我们要找的是最短路径。
\subsubsection{单队列}
\begin{Code}
//LeetCode, Word Ladder II
// 时间复杂度O(n),空间复杂度O(n)
struct state_t {
string word;
int level;
state_t() { word = ""; level = 0; }
state_t(const string& word, int level) {
this->word = word;
this->level = level;
}
bool operator==(const state_t &other) const {
return this->word == other.word;
}
};
namespace std {
template<> struct hash<state_t> {
public:
size_t operator()(const state_t& s) const {
return str_hash(s.word);
}
private:
std::hash<std::string> str_hash;
};
}
class Solution {
public:
vector<vector<string> > findLadders(const string& start,
const string& end, const unordered_set<string> &dict) {
queue<state_t> q;
unordered_set<state_t> visited; // 判重
unordered_map<state_t, vector<state_t> > father; // DAG
auto state_is_valid = [&](const state_t& s) {
return dict.find(s.word) != dict.end() || s.word == end;
};
auto state_is_target = [&](const state_t &s) {return s.word == end; };
auto state_extend = [&](const state_t &s) {
unordered_set<state_t> result;
for (size_t i = 0; i < s.word.size(); ++i) {
state_t new_state(s.word, s.level + 1);
for (char c = 'a'; c <= 'z'; c++) {
// 防止同字母替换
if (c == new_state.word[i]) continue;
swap(c, new_state.word[i]);
if (state_is_valid(new_state)) {
auto visited_iter = visited.find(new_state);
if (visited_iter != visited.end()) {
if (visited_iter->level < new_state.level) {
// do nothing
} else if (visited_iter->level == new_state.level) {
result.insert(new_state);
} else { // not possible
throw std::logic_error("not possible to get here");
}
} else {
result.insert(new_state);
}
}
swap(c, new_state.word[i]); // 恢复该单词
}
}
return result;
};
vector<vector<string>> result;
state_t start_state(start, 0);
q.push(start_state);
visited.insert(start_state);
while (!q.empty()) {
// 千万不能用 const auto&,pop() 会删除元素,
// 引用就变成了悬空引用
const auto state = q.front();
q.pop();
// 如果当前路径长度已经超过当前最短路径长度,
// 可以中止对该路径的处理,因为我们要找的是最短路径
if (!result.empty() && state.level + 1 > result[0].size()) break;
if (state_is_target(state)) {
vector<string> path;
gen_path(father, start_state, state, path, result);
continue;
}
// 必须挪到下面,比如同一层A和B两个节点均指向了目标节点,
// 那么目标节点就会在q中出现两次,输出路径就会翻倍
// visited.insert(state);
// 扩展节点
const auto& new_states = state_extend(state);
for (const auto& new_state : new_states) {
if (visited.find(new_state) == visited.end()) {
q.push(new_state);
}
visited.insert(new_state);
father[new_state].push_back(state);
}
}
return result;
}
private:
void gen_path(unordered_map<state_t, vector<state_t> > &father,
const state_t &start, const state_t &state, vector<string> &path,
vector<vector<string> > &result) {
path.push_back(state.word);
if (state == start) {
if (!result.empty()) {
if (path.size() < result[0].size()) {
result.clear();
result.push_back(path);
reverse(result.back().begin(), result.back().end());
} else if (path.size() == result[0].size()) {
result.push_back(path);
reverse(result.back().begin(), result.back().end());
} else { // not possible
throw std::logic_error("not possible to get here ");
}
} else {
result.push_back(path);
reverse(result.back().begin(), result.back().end());
}
} else {
for (const auto& f : father[state]) {
gen_path(father, start, f, path, result);
}
}
path.pop_back();
}
};
\end{Code}
\subsubsection{双队列}
\begin{Code}
//LeetCode, Word Ladder II
// 时间复杂度O(n),空间复杂度O(n)
class Solution {
public:
vector<vector<string> > findLadders(const string& start,
const string& end, const unordered_set<string> &dict) {
// 当前层,下一层,用unordered_set是为了去重,例如两个父节点指向
// 同一个子节点,如果用vector, 子节点就会在next里出现两次,其实此
// 时 father 已经记录了两个父节点,next里重复出现两次是没必要的
unordered_set<string> current, next;
unordered_set<string> visited; // 判重
unordered_map<string, vector<string> > father; // DAG
int level = -1; // 层次
auto state_is_valid = [&](const string& s) {
return dict.find(s) != dict.end() || s == end;
};
auto state_is_target = [&](const string &s) {return s == end;};
auto state_extend = [&](const string &s) {
unordered_set<string> result;
for (size_t i = 0; i < s.size(); ++i) {
string new_word(s);
for (char c = 'a'; c <= 'z'; c++) {
// 防止同字母替换
if (c == new_word[i]) continue;
swap(c, new_word[i]);
if (state_is_valid(new_word) &&
visited.find(new_word) == visited.end()) {
result.insert(new_word);
}
swap(c, new_word[i]); // 恢复该单词
}
}
return result;
};
vector<vector<string> > result;
current.insert(start);
while (!current.empty()) {
++ level;
// 如果当前路径长度已经超过当前最短路径长度,可以中止对该路径的
// 处理,因为我们要找的是最短路径
if (!result.empty() && level+1 > result[0].size()) break;
// 1. 延迟加入visited, 这样才能允许两个父节点指向同一个子节点
// 2. 一股脑current 全部加入visited, 是防止本层前一个节点扩展
// 节点时,指向了本层后面尚未处理的节点,这条路径必然不是最短的
for (const auto& state : current)
visited.insert(state);
for (const auto& state : current) {
if (state_is_target(state)) {
vector<string> path;
gen_path(father, path, start, state, result);
continue;
}
const auto new_states = state_extend(state);
for (const auto& new_state : new_states) {
next.insert(new_state);
father[new_state].push_back(state);
}
}
current.clear();
swap(current, next);
}
return result;
}
private:
void gen_path(unordered_map<string, vector<string> > &father,
vector<string> &path, const string &start, const string &word,
vector<vector<string> > &result) {
path.push_back(word);
if (word == start) {
if (!result.empty()) {
if (path.size() < result[0].size()) {
result.clear();
result.push_back(path);
} else if(path.size() == result[0].size()) {
result.push_back(path);
} else {
// not possible
throw std::logic_error("not possible to get here");
}
} else {
result.push_back(path);
}
reverse(result.back().begin(), result.back().end());
} else {
for (const auto& f : father[word]) {
gen_path(father, path, start, f, result);
}
}
path.pop_back();
}
};
\end{Code}
\subsubsection{图的广搜}
本题还可以看做是图上的广搜。给定了字典 \fn{dict},可以基于它画出一个无向图,表示单词之间可以互相转换。本题的本质就是已知起点和终点,在图上找出所有最短路径。
\begin{Code}
//LeetCode, Word Ladder II
// 时间复杂度O(n),空间复杂度O(n)
class Solution {
public:
vector<vector<string> > findLadders(const string& start,
const string &end, const unordered_set<string> &dict) {
const auto& g = build_graph(dict);
vector<state_t*> pool;
queue<state_t*> q; // 未处理的节点
// value 是所在层次
unordered_map<string, int> visited;
auto state_is_target = [&](const state_t *s) {return s->word == end; };
vector<vector<string>> result;
q.push(create_state(nullptr, start, 0, pool));
while (!q.empty()) {
state_t* state = q.front();
q.pop();
// 如果当前路径长度已经超过当前最短路径长度,
// 可以中止对该路径的处理,因为我们要找的是最短路径
if (!result.empty() && state->level+1 > result[0].size()) break;
if (state_is_target(state)) {
const auto& path = gen_path(state);
if (result.empty()) {
result.push_back(path);
} else {
if (path.size() < result[0].size()) {
result.clear();
result.push_back(path);
} else if (path.size() == result[0].size()) {
result.push_back(path);
} else {
// not possible
throw std::logic_error("not possible to get here");
}
}
continue;
}
visited[state->word] = state->level;
// 扩展节点
auto iter = g.find(state->word);
if (iter == g.end()) continue;
for (const auto& neighbor : iter->second) {
auto visited_iter = visited.find(neighbor);
if (visited_iter != visited.end() &&
visited_iter->second < state->level + 1) {
continue;
}
q.push(create_state(state, neighbor, state->level + 1, pool));
}
}
// release all states
for (auto state : pool) {
delete state;
}
return result;
}
private:
struct state_t {
state_t* father;
string word;
int level; // 所在层次,从0开始编号
state_t(state_t* father_, const string& word_, int level_) :
father(father_), word(word_), level(level_) {}
};
state_t* create_state(state_t* parent, const string& value,
int length, vector<state_t*>& pool) {
state_t* node = new state_t(parent, value, length);
pool.push_back(node);
return node;
}
vector<string> gen_path(const state_t* node) {
vector<string> path;
while(node != nullptr) {
path.push_back(node->word);
node = node->father;
}
reverse(path.begin(), path.end());
return path;
}
unordered_map<string, unordered_set<string> > build_graph(
const unordered_set<string>& dict) {
unordered_map<string, unordered_set<string> > adjacency_list;
for (const auto& word : dict) {
for (size_t i = 0; i < word.size(); ++i) {
string new_word(word);
for (char c = 'a'; c <= 'z'; c++) {
// 防止同字母替换
if (c == new_word[i]) continue;
swap(c, new_word[i]);
if ((dict.find(new_word) != dict.end())) {
auto iter = adjacency_list.find(word);
if (iter != adjacency_list.end()) {
iter->second.insert(new_word);
} else {
adjacency_list.insert(pair<string,
unordered_set<string>>(word, unordered_set<string>()));
adjacency_list[word].insert(new_word);
}
}
swap(c, new_word[i]); // 恢复该单词
}
}
}
return adjacency_list;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Word Ladder,见 \S \ref{sec:word-ladder}
\myenddot
\section{Surrounded Regions} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:surrounded-regions}
\subsubsection{描述}
Given a 2D board containing \fn{'X'} and \fn{'O'}, capture all regions surrounded by \fn{'X'}.
A region is captured by flipping all \fn{'O'}s into \fn{'X'}s in that surrounded region .
For example,
\begin{Code}
X X X X
X O O X
X X O X
X O X X
\end{Code}
After running your function, the board should be:
\begin{Code}
X X X X
X X X X
X X X X
X O X X
\end{Code}
\subsubsection{分析}
广搜。从上下左右四个边界往里走,凡是能碰到的\fn{'O'},都是跟边界接壤的,应该保留。
\subsubsection{代码}
\begin{Code}
// LeetCode, Surrounded Regions
// BFS,时间复杂度O(n),空间复杂度O(n)
class Solution {
public:
void solve(vector<vector<char>> &board) {
if (board.empty()) return;
const int m = board.size();
const int n = board[0].size();
for (int i = 0; i < n; i++) {
bfs(board, 0, i);
bfs(board, m - 1, i);
}
for (int j = 1; j < m - 1; j++) {
bfs(board, j, 0);
bfs(board, j, n - 1);
}
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
if (board[i][j] == 'O')
board[i][j] = 'X';
else if (board[i][j] == '+')
board[i][j] = 'O';
}
private:
void bfs(vector<vector<char>> &board, int i, int j) {
typedef pair<int, int> state_t;
queue<state_t> q;
const int m = board.size();
const int n = board[0].size();
auto state_is_valid = [&](const state_t &s) {
const int x = s.first;
const int y = s.second;
if (x < 0 || x >= m || y < 0 || y >= n || board[x][y] != 'O')
return false;
return true;
};
auto state_extend = [&](const state_t &s) {
vector<state_t> result;
const int x = s.first;
const int y = s.second;
// 上下左右
const state_t new_states[4] = {{x-1,y}, {x+1,y},
{x,y-1}, {x,y+1}};
for (int k = 0; k < 4; ++k) {
if (state_is_valid(new_states[k])) {
// 既有标记功能又有去重功能
board[new_states[k].first][new_states[k].second] = '+';
result.push_back(new_states[k]);
}
}
return result;
};
state_t start = { i, j };
if (state_is_valid(start)) {
board[i][j] = '+';
q.push(start);
}
while (!q.empty()) {
auto cur = q.front();
q.pop();
auto new_states = state_extend(cur);
for (auto s : new_states) q.push(s);
}
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item 无
\myenddot
\section{小结} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:bfs-template}
\subsection{适用场景}
\textbf{输入数据}:没什么特征,不像深搜,需要有“递归”的性质。如果是树或者图,概率更大。
\textbf{状态转换图}:树或者DAG图。
\textbf{求解目标}:求最短。
\subsection{思考的步骤}
\begin{enumerate}
\item 是求路径长度,还是路径本身(或动作序列)?
\begin{enumerate}
\item 如果是求路径长度,则状态里面要存路径长度(或双队列+一个全局变量)
\item 如果是求路径本身或动作序列
\begin{enumerate}
\item 要用一棵树存储宽搜过程中的路径
\item 是否可以预估状态个数的上限?能够预估状态总数,则开一个大数组,用树的双亲表示法;如果不能预估状态总数,则要使用一棵通用的树。这一步也是第4步的必要不充分条件。
\end{enumerate}
\end{enumerate}
\item 如何表示状态?即一个状态需要存储哪些些必要的数据,才能够完整提供如何扩展到下一步状态的所有信息。一般记录当前位置或整体局面。
\item 如何扩展状态?这一步跟第2步相关。状态里记录的数据不同,扩展方法就不同。对于固定不变的数据结构(一般题目直接给出,作为输入数据),如二叉树,图等,扩展方法很简单,直接往下一层走,对于隐式图,要先在第1步里想清楚状态所带的数据,想清楚了这点,那如何扩展就很简单了。
\item 如何判断重复?如果状态转换图是一颗树,则永远不会出现回路,不需要判重;如果状态转换图是一个图(这时候是一个图上的BFS),则需要判重。
\begin{enumerate}
\item 如果是求最短路径长度或一条路径,则只需要让“点”(即状态)不重复出现,即可保证不出现回路
\item 如果是求所有路径,注意此时,状态转换图是DAG,即允许两个父节点指向同一个子节点。具体实现时,每个节点要\textbf{“延迟”}加入到已访问集合\fn{visited},要等一层全部访问完后,再加入到\fn{visited}集合。
\item 具体实现
\begin{enumerate}
\item 状态是否存在完美哈希方案?即将状态一一映射到整数,互相之间不会冲突。
\item 如果不存在,则需要使用通用的哈希表(自己实现或用标准库,例如\fn{unordered_set})来判重;自己实现哈希表的话,如果能够预估状态个数的上限,则可以开两个数组,head和next,表示哈希表,参考第 \S \ref{subsec:eightDigits}节方案2。
\item 如果存在,则可以开一个大布尔数组,来判重,且此时可以精确计算出状态总数,而不仅仅是预估上限。
\end{enumerate}
\end{enumerate}
\item 目标状态是否已知?如果题目已经给出了目标状态,可以带来很大便利,这时候可以从起始状态出发,正向广搜;也可以从目标状态出发,逆向广搜;也可以同时出发,双向广搜。
\end{enumerate}
\subsection{代码模板}
广搜需要一个队列,用于一层一层扩展,一个hashset,用于判重,一棵树(只求长度时不需要),用于存储整棵树。
对于队列,可以用\fn{queue},也可以把\fn{vector}当做队列使用。当求长度时,有两种做法:
\begin{enumerate}
\item 只用一个队列,但在状态结构体\fn{state_t}里增加一个整数字段\fn{level},表示当前所在的层次,当碰到目标状态,直接输出\fn{level}即可。这个方案,可以很容易的变成A*算法,把\fn{queue}替换为\fn{priority_queue}即可。
\item 用两个队列,\fn{current, next},分别表示当前层次和下一层,另设一个全局整数\fn{level},表示层数(也即路径长度),当碰到目标状态,输出\fn{level}即可。这个方案,状态里可以不存路径长度,只需全局设置一个整数\fn{level},比较节省内存;
\end{enumerate}
对于hashset,如果有完美哈希方案,用布尔数组(\fn{bool visited[STATE_MAX]}或\fn{vector<bool> visited(STATE_MAX, false)})来表示;如果没有,可以用STL里的\fn{set}或\fn{unordered_set}。
对于树,如果用STL,可以用\fn{unordered_map<state_t, state_t > father}表示一颗树,代码非常简洁。如果能够预估状态总数的上限(设为STATE_MAX),可以用数组(\fn{state_t nodes[STATE_MAX]}),即树的双亲表示法来表示树,效率更高,当然,需要写更多代码。
\subsubsection{如何表示状态}
\begin{Codex}[label=bfs_common.h]
/** 状态 */
struct state_t {
int data1; /** 状态的数据,可以有多个字段. */
int data2; /** 状态的数据,可以有多个字段. */
// dataN; /** 其他字段 */
int action; /** 由父状态移动到本状态的动作,求动作序列时需要. */
int level; /** 所在的层次(从0开始),也即路径长度-1,求路径长度时需要;
不过,采用双队列时不需要本字段,只需全局设一个整数 */
bool operator==(const state_t &other) const {
return true; // 根据具体问题实现
}
};
// 定义hash函数
// 方法1:模板特化,当hash函数只需要状态本身,不需要其他数据时,用这个方法比较简洁
namespace std {
template<> struct hash<state_t> {
size_t operator()(const state_t & x) const {
return 0; // 根据具体问题实现
}
};
}
// 方法2:函数对象,如果hash函数需要运行时数据,则用这种方法
class Hasher {
public:
Hasher(int _m) : m(_m) {};
size_t operator()(const state_t &s) const {
return 0; // 根据具体问题实现
}
private:
int m; // 存放外面传入的数据
};
/**
* @brief 反向生成路径,求一条路径.
* @param[in] father 树
* @param[in] target 目标节点
* @return 从起点到target的路径
*/
vector<state_t> gen_path(const unordered_map<state_t, state_t> &father,
const state_t &target) {
vector<state_t> path;
path.push_back(target);
for (state_t cur = target; father.find(cur) != father.end();
cur = father.at(cur))
path.push_back(cur);
reverse(path.begin(), path.end());
return path;
}
/**
* 反向生成路径,求所有路径.
* @param[in] father 存放了所有路径的树
* @param[in] start 起点
* @param[in] state 终点
* @return 从起点到终点的所有路径
*/
void gen_path(unordered_map<state_t, vector<state_t> > &father,
const string &start, const state_t& state, vector<state_t> &path,
vector<vector<state_t> > &result) {
path.push_back(state);
if (state == start) {
if (!result.empty()) {
if (path.size() < result[0].size()) {
result.clear();
result.push_back(path);
} else if(path.size() == result[0].size()) {
result.push_back(path);
} else {
// not possible
throw std::logic_error("not possible to get here");
}
} else {
result.push_back(path);
}
reverse(result.back().begin(), result.back().end());
} else {
for (const auto& f : father[state]) {
gen_path(father, start, f, path, result);
}
}
path.pop_back();
}
\end{Codex}
\subsubsection{求最短路径长度或一条路径}
\textbf{单队列的写法}
\begin{Codex}[label=bfs_template.cpp]
#include "bfs_common.h"
/**
* @brief 广搜,只用一个队列.
* @param[in] start 起点
* @param[in] data 输入数据
* @return 从起点到目标状态的一条最短路径
*/
vector<state_t> bfs(state_t &start, const vector<vector<int>> &grid) {
queue<state_t> q; // 队列
unordered_set<state_t> visited; // 判重
unordered_map<state_t, state_t> father; // 树,求路径本身时才需要
// 判断状态是否合法
auto state_is_valid = [&](const state_t &s) { /*...*/ };
// 判断当前状态是否为所求目标
auto state_is_target = [&](const state_t &s) { /*...*/ };
// 扩展当前状态
auto state_extend = [&](const state_t &s) {
unordered_set<state_t> result;
for (/*...*/) {
const state_t new_state = /*...*/;
if (state_is_valid(new_state) &&
visited.find(new_state) != visited.end()) {
result.insert(new_state);
}
}
return result;
};
assert (start.level == 0);
q.push(start);
while (!q.empty()) {
// 千万不能用 const auto&,pop() 会删除元素,
// 引用就变成了悬空引用
const state_t state = q.front();
q.pop();
visited.insert(state);
// 访问节点
if (state_is_target(state)) {
return return gen_path(father, target); // 求一条路径
// return state.level + 1; // 求路径长度
}
// 扩展节点
vector<state_t> new_states = state_extend(state);
for (const auto& new_state : new_states) {
q.push(new_state);
father[new_state] = state; // 求一条路径
// visited.insert(state); // 优化:可以提前加入 visited 集合,
// 从而缩小状态扩展。这时 q 的含义略有变化,里面存放的是处理了一半
// 的节点:已经加入了visited,但还没有扩展。别忘记 while循环开始
// 前,要加一行代码, visited.insert(start)
}
}
return vector<state_t>();
//return 0;
}
\end{Codex}
\textbf{双队列的写法}
\begin{Codex}[label=bfs_template1.cpp]
#include "bfs_common.h"
/**
* @brief 广搜,使用两个队列.
* @param[in] start 起点
* @param[in] data 输入数据
* @return 从起点到目标状态的一条最短路径
*/
vector<state_t> bfs(const state_t &start, const type& data) {
queue<state_t> next, current; // 当前层,下一层
unordered_set<state_t> visited; // 判重
unordered_map<state_t, state_t> father; // 树,求路径本身时才需要
int level = -1; // 层次
// 判断状态是否合法
auto state_is_valid = [&](const state_t &s) { /*...*/ };
// 判断当前状态是否为所求目标
auto state_is_target = [&](const state_t &s) { /*...*/ };
// 扩展当前状态
auto state_extend = [&](const state_t &s) {
unordered_set<state_t> result;
for (/*...*/) {
const state_t new_state = /*...*/;
if (state_is_valid(new_state) &&
visited.find(new_state) != visited.end()) {
result.insert(new_state);
}
}
return result;
};
current.push(start);
while (!current.empty()) {
++level;
while (!current.empty()) {
// 千万不能用 const auto&,pop() 会删除元素,
// 引用就变成了悬空引用
const auto state = current.front();
current.pop();
visited.insert(state);
if (state_is_target(state)) {
return return gen_path(father, state); // 求一条路径
// return state.level + 1; // 求路径长度
}
const auto& new_states = state_extend(state);
for (const auto& new_state : new_states) {
next.push(new_state);
father[new_state] = state;
// visited.insert(state); // 优化:可以提前加入 visited 集合,
// 从而缩小状态扩展。这时 current 的含义略有变化,里面存放的是处
// 理了一半的节点:已经加入了visited,但还没有扩展。别忘记 while
// 循环开始前,要加一行代码, visited.insert(start)
}
}
swap(next, current); //!!! 交换两个队列
}
return vector<state_t>();
// return 0;
}
\end{Codex}
\subsubsection{求所有路径}
\textbf{单队列}
\begin{Codex}[label=bfs_template.cpp]
/**
* @brief 广搜,使用一个队列.
* @param[in] start 起点
* @param[in] data 输入数据
* @return 从起点到目标状态的所有最短路径
*/
vector<vector<state_t> > bfs(const state_t &start, const type& data) {
queue<state_t> q;
unordered_set<state_t> visited; // 判重
unordered_map<state_t, vector<state_t> > father; // DAG
auto state_is_valid = [&](const state_t& s) { /*...*/ };
auto state_is_target = [&](const state_t &s) { /*...*/ };
auto state_extend = [&](const state_t &s) {
unordered_set<state_t> result;
for (/*...*/) {
const state_t new_state = /*...*/;
if (state_is_valid(new_state)) {
auto visited_iter = visited.find(new_state);
if (visited_iter != visited.end()) {
if (visited_iter->level < new_state.level) {
// do nothing
} else if (visited_iter->level == new_state.level) {
result.insert(new_state);
} else { // not possible
throw std::logic_error("not possible to get here");
}
} else {
result.insert(new_state);
}
}
}
return result;
};
vector<vector<string>> result;
state_t start_state(start, 0);
q.push(start_state);
visited.insert(start_state);
while (!q.empty()) {
// 千万不能用 const auto&,pop() 会删除元素,
// 引用就变成了悬空引用
const auto state = q.front();
q.pop();
// 如果当前路径长度已经超过当前最短路径长度,
// 可以中止对该路径的处理,因为我们要找的是最短路径
if (!result.empty() && state.level + 1 > result[0].size()) break;
if (state_is_target(state)) {
vector<string> path;
gen_path(father, start_state, state, path, result);
continue;
}
// 必须挪到下面,比如同一层A和B两个节点均指向了目标节点,
// 那么目标节点就会在q中出现两次,输出路径就会翻倍
// visited.insert(state);
// 扩展节点
const auto& new_states = state_extend(state);
for (const auto& new_state : new_states) {
if (visited.find(new_state) == visited.end()) {
q.push(new_state);
}
visited.insert(new_state);
father[new_state].push_back(state);
}
}
return result;
}
\end{Codex}
\textbf{双队列的写法}
\begin{Codex}[label=bfs_template.cpp]
#include "bfs_common.h"
/**
* @brief 广搜,使用两个队列.
* @param[in] start 起点
* @param[in] data 输入数据
* @return 从起点到目标状态的所有最短路径
*/
vector<vector<state_t> > bfs(const state_t &start, const type& data) {
// 当前层,下一层,用unordered_set是为了去重,例如两个父节点指向
// 同一个子节点,如果用vector, 子节点就会在next里出现两次,其实此
// 时 father 已经记录了两个父节点,next里重复出现两次是没必要的
unordered_set<string> current, next;
unordered_set<state_t> visited; // 判重
unordered_map<state_t, vector<state_t> > father; // DAG
int level = -1; // 层次
// 判断状态是否合法
auto state_is_valid = [&](const state_t &s) { /*...*/ };
// 判断当前状态是否为所求目标
auto state_is_target = [&](const state_t &s) { /*...*/ };
// 扩展当前状态
auto state_extend = [&](const state_t &s) {
unordered_set<state_t> result;
for (/*...*/) {
const state_t new_state = /*...*/;
if (state_is_valid(new_state) &&
visited.find(new_state) != visited.end()) {
result.insert(new_state);
}
}
return result;
};
vector<vector<state_t> > result;
current.insert(start);
while (!current.empty()) {
++ level;
// 如果当前路径长度已经超过当前最短路径长度,可以中止对该路径的
// 处理,因为我们要找的是最短路径
if (!result.empty() && level+1 > result[0].size()) break;
// 1. 延迟加入visited, 这样才能允许两个父节点指向同一个子节点
// 2. 一股脑current 全部加入visited, 是防止本层前一个节点扩展
// 节点时,指向了本层后面尚未处理的节点,这条路径必然不是最短的
for (const auto& state : current)
visited.insert(state);
for (const auto& state : current) {
if (state_is_target(state)) {
vector<string> path;
gen_path(father, path, start, state, result);
continue;
}
const auto new_states = state_extend(state);
for (const auto& new_state : new_states) {
next.insert(new_state);
father[new_state].push_back(state);
}
}
current.clear();
swap(current, next);
}
return result;
}
\end{Codex}
================================================
FILE: C++/chapBruteforce.tex
================================================
\chapter{暴力枚举法}
\section{Subsets} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:subsets}
\subsubsection{描述}
Given a set of distinct integers, $S$, return all possible subsets.
Note:
\begindot
\item Elements in a subset must be in non-descending order.
\item The solution set must not contain duplicate subsets.
\myenddot
For example, If \code{S = [1,2,3]}, a solution is:
\begin{Code}
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
\end{Code}
\subsection{递归}
\subsubsection{增量构造法}
每个元素,都有两种选择,选或者不选。
\begin{Code}
// LeetCode, Subsets
// 增量构造法,深搜,时间复杂度O(2^n),空间复杂度O(n)
class Solution {
public:
vector<vector<int> > subsets(vector<int> &S) {
sort(S.begin(), S.end()); // 输出要求有序
vector<vector<int> > result;
vector<int> path;
subsets(S, path, 0, result);
return result;
}
private:
static void subsets(const vector<int> &S, vector<int> &path, int step,
vector<vector<int> > &result) {
if (step == S.size()) {
result.push_back(path);
return;
}
// 不选S[step]
subsets(S, path, step + 1, result);
// 选S[step]
path.push_back(S[step]);
subsets(S, path, step + 1, result);
path.pop_back();
}
};
\end{Code}
\subsubsection{位向量法}
开一个位向量\fn{bool selected[n]},每个元素可以选或者不选。
\begin{Code}
// LeetCode, Subsets
// 位向量法,深搜,时间复杂度O(2^n),空间复杂度O(n)
class Solution {
public:
vector<vector<int> > subsets(vector<int> &S) {
sort(S.begin(), S.end()); // 输出要求有序
vector<vector<int> > result;
vector<bool> selected(S.size(), false);
subsets(S, selected, 0, result);
return result;
}
private:
static void subsets(const vector<int> &S, vector<bool> &selected, int step,
vector<vector<int> > &result) {
if (step == S.size()) {
vector<int> subset;
for (int i = 0; i < S.size(); i++) {
if (selected[i]) subset.push_back(S[i]);
}
result.push_back(subset);
return;
}
// 不选S[step]
selected[step] = false;
subsets(S, selected, step + 1, result);
// 选S[step]
selected[step] = true;
subsets(S, selected, step + 1, result);
}
};
\end{Code}
\subsection{迭代}
\subsubsection{增量构造法}
\begin{Code}
// LeetCode, Subsets
// 迭代版,时间复杂度O(2^n),空间复杂度O(1)
class Solution {
public:
vector<vector<int> > subsets(vector<int> &S) {
sort(S.begin(), S.end()); // 输出要求有序
vector<vector<int> > result(1);
for (auto elem : S) {
result.reserve(result.size() * 2);
auto half = result.begin() + result.size();
copy(result.begin(), half, back_inserter(result));
for_each(half, result.end(), [&elem](decltype(result[0]) &e){
e.push_back(elem);
});
}
return result;
}
};
\end{Code}
\subsubsection{二进制法}
本方法的前提是:集合的元素不超过int位数。用一个int整数表示位向量,第$i$位为1,则表示选择$S[i]$,为0则不选择。例如\fn{S=\{A,B,C,D\}},则\fn{0110=6}表示子集\fn{\{B,C\}}。
这种方法最巧妙。因为它不仅能生成子集,还能方便的表示集合的并、交、差等集合运算。设两个集合的位向量分别为$B_1$和$B_2$,则$B_1\cup B_2, B_1 \cap B_2, B_1 \triangle B_2$分别对应集合的并、交、对称差。
二进制法,也可以看做是位向量法,只不过更加优化。
\begin{Code}
// LeetCode, Subsets
// 二进制法,时间复杂度O(2^n),空间复杂度O(1)
class Solution {
public:
vector<vector<int> > subsets(vector<int> &S) {
sort(S.begin(), S.end()); // 输出要求有序
vector<vector<int> > result;
const size_t n = S.size();
vector<int> v;
for (size_t i = 0; i < 1 << n; i++) {
for (size_t j = 0; j < n; j++) {
if (i & 1 << j) v.push_back(S[j]);
}
result.push_back(v);
v.clear();
}
return result;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Subsets II,见 \S \ref{sec:subsets-ii}
\myenddot
\section{Subsets II} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:subsets-ii}
\subsubsection{描述}
Given a collection of integers that might contain duplicates, $S$, return all possible subsets.
Note:
Elements in a subset must be in non-descending order.
The solution set must not contain duplicate subsets.
For example,
If \fn{S = [1,2,2]}, a solution is:
\begin{Code}
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
\end{Code}
\subsubsection{分析}
这题有重复元素,但本质上,跟上一题很类似,上一题中元素没有重复,相当于每个元素只能选0或1次,这里扩充到了每个元素可以选0到若干次而已。
\subsection{递归}
\subsubsection{增量构造法}
\begin{Code}
// LeetCode, Subsets II
// 增量构造法,版本1,时间复杂度O(2^n),空间复杂度O(n)
class Solution {
public:
vector<vector<int> > subsetsWithDup(vector<int> &S) {
sort(S.begin(), S.end()); // 必须排序
vector<vector<int> > result;
vector<int> path;
dfs(S, S.begin(), path, result);
return result;
}
private:
static void dfs(const vector<int> &S, vector<int>::iterator start,
vector<int> &path, vector<vector<int> > &result) {
result.push_back(path);
for (auto i = start; i < S.end(); i++) {
if (i != start && *i == *(i-1)) continue;
path.push_back(*i);
dfs(S, i + 1, path, result);
path.pop_back();
}
}
};
\end{Code}
\begin{Code}
// LeetCode, Subsets II
// 增量构造法,版本2,时间复杂度O(2^n),空间复杂度O(n)
class Solution {
public:
vector<vector<int> > subsetsWithDup(vector<int> &S) {
vector<vector<int> > result;
sort(S.begin(), S.end()); // 必须排序
unordered_map<int, int> count_map; // 记录每个元素的出现次数
for_each(S.begin(), S.end(), [&count_map](int e) {
if (count_map.find(e) != count_map.end())
count_map[e]++;
else
count_map[e] = 1;
});
// 将map里的pair拷贝到一个vector里
vector<pair<int, int> > elems;
for_each(count_map.begin(), count_map.end(),
[&elems](const pair<int, int> &e) {
elems.push_back(e);
});
sort(elems.begin(), elems.end());
vector<int> path; // 中间结果
subsets(elems, 0, path, result);
return result;
}
private:
static void subsets(const vector<pair<int, int> > &elems,
size_t step, vector<int> &path, vector<vector<int> > &result) {
if (step == elems.size()) {
result.push_back(path);
return;
}
for (int i = 0; i <= elems[step].second; i++) {
for (int j = 0; j < i; ++j) {
path.push_back(elems[step].first);
}
subsets(elems, step + 1, path, result);
for (int j = 0; j < i; ++j) {
path.pop_back();
}
}
}
};
\end{Code}
\subsubsection{位向量法}
\begin{Code}
// LeetCode, Subsets II
// 位向量法,时间复杂度O(2^n),空间复杂度O(n)
class Solution {
public:
vector<vector<int> > subsetsWithDup(vector<int> &S) {
vector<vector<int> > result; // 必须排序
sort(S.begin(), S.end());
vector<int> count(S.back() - S.front() + 1, 0);
// 计算所有元素的个数
for (auto i : S) {
count[i - S[0]]++;
}
// 每个元素选择了多少个
vector<int> selected(S.back() - S.front() + 1, -1);
subsets(S, count, selected, 0, result);
return result;
}
private:
static void subsets(const vector<int> &S, vector<int> &count,
vector<int> &selected, size_t step, vector<vector<int> > &result) {
if (step == count.size()) {
vector<int> subset;
for(size_t i = 0; i < selected.size(); i++) {
for (int j = 0; j < selected[i]; j++) {
subset.push_back(i+S[0]);
}
}
result.push_back(subset);
return;
}
for (int i = 0; i <= count[step]; i++) {
selected[step] = i;
subsets(S, count, selected, step + 1, result);
}
}
};
\end{Code}
\subsection{迭代}
\subsubsection{增量构造法}
\begin{Code}
// LeetCode, Subsets II
// 增量构造法
// 时间复杂度O(2^n),空间复杂度O(1)
class Solution {
public:
vector<vector<int> > subsetsWithDup(vector<int> &S) {
sort(S.begin(), S.end()); // 必须排序
vector<vector<int> > result(1);
size_t previous_size = 0;
for (size_t i = 0; i < S.size(); ++i) {
const size_t size = result.size();
for (size_t j = 0; j < size; ++j) {
if (i == 0 || S[i] != S[i-1] || j >= previous_size) {
result.push_back(result[j]);
result.back().push_back(S[i]);
}
}
previous_size = size;
}
return result;
}
};
\end{Code}
\subsubsection{二进制法}
\begin{Code}
// LeetCode, Subsets II
// 二进制法,时间复杂度O(2^n),空间复杂度O(1)
class Solution {
public:
vector<vector<int> > subsetsWithDup(vector<int> &S) {
sort(S.begin(), S.end()); // 必须排序
// 用 set 去重,不能用 unordered_set,因为输出要求有序
set<vector<int> > result;
const size_t n = S.size();
vector<int> v;
for (size_t i = 0; i < 1U << n; ++i) {
for (size_t j = 0; j < n; ++j) {
if (i & 1 << j)
v.push_back(S[j]);
}
result.insert(v);
v.clear();
}
vector<vector<int> > real_result;
copy(result.begin(), result.end(), back_inserter(real_result));
return real_result;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Subsets,见 \S \ref{sec:subsets}
\myenddot
\section{Permutations} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:permutations}
\subsubsection{描述}
Given a collection of numbers, return all possible permutations.
For example,
\fn{[1,2,3]} have the following permutations:
\fn{[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2]}, and \fn{[3,2,1]}.
\subsection{next_permutation()}
偷懒的做法,可以直接使用\fn{std::next_permutation()}。如果是在OJ网站上,可以用这个API偷个懒;如果是在面试中,面试官肯定会让你重新实现。
\subsubsection{代码}
\begin{Code}
// LeetCode, Permutations
// 时间复杂度O(n!),空间复杂度O(1)
class Solution {
public:
vector<vector<int> > permute(vector<int> &num) {
vector<vector<int> > result;
sort(num.begin(), num.end());
do {
result.push_back(num);
} while(next_permutation(num.begin(), num.end()));
return result;
}
};
\end{Code}
\subsection{重新实现next_permutation()}
见第 \S \ref{sec:next-permutation} 节。
\subsubsection{代码}
\begin{Code}
// LeetCode, Permutations
// 重新实现 next_permutation()
// 时间复杂度O(n!),空间复杂度O(1)
class Solution {
public:
vector<vector<int> > permute(vector<int> &num) {
vector<vector<int> > result;
sort(num.begin(), num.end());
do {
result.push_back(num);
// 调用的是 2.1.12 节的 next_permutation()
// 而不是 std::next_permutation()
} while(next_permutation(num.begin(), num.end()));
return result;
}
};
\end{Code}
\subsection{递归}
本题是求路径本身,求所有解,函数参数需要标记当前走到了哪步,还需要中间结果的引用,最终结果的引用。
扩展节点,每次从左到右,选一个没有出现过的元素。
本题不需要判重,因为状态装换图是一颗有层次的树。收敛条件是当前走到了最后一个元素。
\subsubsection{代码}
\begin{Code}
// LeetCode, Permutations
// 深搜,增量构造法
// 时间复杂度O(n!),空间复杂度O(n)
class Solution {
public:
vector<vector<int> > permute(vector<int>& num) {
sort(num.begin(), num.end());
vector<vector<int>> result;
vector<int> path; // 中间结果
dfs(num, path, result);
return result;
}
private:
void dfs(const vector<int>& num, vector<int> &path,
vector<vector<int> > &result) {
if (path.size() == num.size()) { // 收敛条件
result.push_back(path);
return;
}
// 扩展状态
for (auto i : num) {
// 查找 i 是否在path 中出现过
auto pos = find(path.begin(), path.end(), i);
if (pos == path.end()) {
path.push_back(i);
dfs(num, path, result);
path.pop_back();
}
}
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Next Permutation, 见 \S \ref{sec:next-permutation}
\item Permutation Sequence, 见 \S \ref{sec:permutation-sequence}
\item Permutations II, 见 \S \ref{sec:permutations-ii}
\item Combinations, 见 \S \ref{sec:combinations}
\myenddot
\section{Permutations II} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:permutations-ii}
\subsubsection{描述}
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
For example,
\fn{[1,1,2]} have the following unique permutations:
\fn{[1,1,2], [1,2,1]}, and \fn{[2,1,1]}.
\subsection{next_permutation()}
直接使用\fn{std::next_permutation()},代码与上一题相同。
\subsection{重新实现next_permutation()}
重新实现\fn{std::next_permutation()},代码与上一题相同。
\subsection{递归}
递归函数\fn{permute()}的参数\fn{p},是中间结果,它的长度又能标记当前走到了哪一步,用于判断收敛条件。
扩展节点,每次从小到大,选一个没有被用光的元素,直到所有元素被用光。
本题不需要判重,因为状态装换图是一颗有层次的树。
\subsubsection{代码}
\begin{Code}
// LeetCode, Permutations II
// 深搜,时间复杂度O(n!),空间复杂度O(n)
class Solution {
public:
vector<vector<int> > permuteUnique(vector<int>& num) {
sort(num.begin(), num.end());
unordered_map<int, int> count_map; // 记录每个元素的出现次数
for_each(num.begin(), num.end(), [&count_map](int e) {
if (count_map.find(e) != count_map.end())
count_map[e]++;
else
count_map[e] = 1;
});
// 将map里的pair拷贝到一个vector里
vector<pair<int, int> > elems;
for_each(count_map.begin(), count_map.end(),
[&elems](const pair<int, int> &e) {
elems.push_back(e);
});
vector<vector<int>> result; // 最终结果
vector<int> p; // 中间结果
n = num.size();
permute(elems.begin(), elems.end(), p, result);
return result;
}
private:
size_t n;
typedef vector<pair<int, int> >::const_iterator Iter;
void permute(Iter first, Iter last, vector<int> &p,
vector<vector<int> > &result) {
if (n == p.size()) { // 收敛条件
result.push_back(p);
}
// 扩展状态
for (auto i = first; i != last; i++) {
int count = 0; // 统计 *i 在p中出现过多少次
for (auto j = p.begin(); j != p.end(); j++) {
if (i->first == *j) {
count ++;
}
}
if (count < i->second) {
p.push_back(i->first);
permute(first, last, p, result);
p.pop_back(); // 撤销动作,返回上一层
}
}
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Next Permutation, 见 \S \ref{sec:next-permutation}
\item Permutation Sequence, 见 \S \ref{sec:permutation-sequence}
\item Permutations, 见 \S \ref{sec:permutations}
\item Combinations, 见 \S \ref{sec:combinations}
\myenddot
\section{Combinations} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:combinations}
\subsubsection{描述}
Given two integers $n$ and $k$, return all possible combinations of $k$ numbers out of $1 ... n$.
For example,
If $n = 4$ and $k = 2$, a solution is:
\begin{Code}
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
\end{Code}
\subsection{递归}
\begin{Code}
// LeetCode, Combinations
// 深搜,递归
// 时间复杂度O(n!),空间复杂度O(n)
class Solution {
public:
vector<vector<int> > combine(int n, int k) {
vector<vector<int> > result;
vector<int> path;
dfs(n, k, 1, 0, path, result);
return result;
}
private:
// start,开始的数, cur,已经选择的数目
static void dfs(int n, int k, int start, int cur,
vector<int> &path, vector<vector<int> > &result) {
if (cur == k) {
result.push_back(path);
}
for (int i = start; i <= n; ++i) {
path.push_back(i);
dfs(n, k, i + 1, cur + 1, path, result);
path.pop_back();
}
}
};
\end{Code}
\subsection{迭代}
\begin{Code}
// LeetCode, Combinations
// use prev_permutation()
// 时间复杂度O((n-k)!),空间复杂度O(n)
class Solution {
public:
vector<vector<int> > combine(int n, int k) {
vector<int> values(n);
iota(values.begin(), values.end(), 1);
vector<bool> select(n, false);
fill_n(select.begin(), k, true);
vector<vector<int> > result;
do{
vector<int> one(k);
for (int i = 0, index = 0; i < n; ++i)
if (select[i])
one[index++] = values[i];
result.push_back(one);
} while(prev_permutation(select.begin(), select.end()));
return result;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Next Permutation, 见 \S \ref{sec:next-permutation}
\item Permutation Sequence, 见 \S \ref{sec:permutation-sequence}
\item Permutations, 见 \S \ref{sec:permutations}
\item Permutations II, 见 \S \ref{sec:permutations-ii}
\myenddot
\section{Letter Combinations of a Phone Number } %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:letter-combinations-of-a-phone-number }
\subsubsection{描述}
Given a digit string, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below.
\begin{center}
\includegraphics[width=150pt]{phone-keyboard.png}\\
\figcaption{Phone Keyboard}\label{fig:phone-keyboard}
\end{center}
\textbf{Input:}Digit string \code{"23"}
\textbf{Output:} \code{["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]}.
\textbf{Note:}
Although the above answer is in lexicographical order, your answer could be in any order you want.
\subsubsection{分析}
无
\subsection{递归}
\begin{Code}
// LeetCode, Letter Combinations of a Phone Number
// 时间复杂度O(3^n),空间复杂度O(n)
class Solution {
public:
const vector<string> keyboard { " ", "", "abc", "def", // '0','1','2',...
"ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
vector<string> letterCombinations (const string &digits) {
vector<string> result;
if (digits.empty()) return result;
dfs(digits, 0, "", result);
return result;
}
void dfs(const string &digits, size_t cur, string path,
vector<string> &result) {
if (cur == digits.size()) {
result.push_back(path);
return;
}
for (auto c : keyboard[digits[cur] - '0']) {
dfs(digits, cur + 1, path + c, result);
}
}
};
\end{Code}
\subsection{迭代}
\begin{Code}
// LeetCode, Letter Combinations of a Phone Number
// 时间复杂度O(3^n),空间复杂度O(1)
class Solution {
public:
const vector<string> keyboard { " ", "", "abc", "def", // '0','1','2',...
"ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
vector<string> letterCombinations (const string &digits) {
if (digits.empty()) return vector<string>();
vector<string> result(1, "");
for (auto d : digits) {
const size_t n = result.size();
const size_t m = keyboard[d - '0'].size();
result.resize(n * m);
for (size_t i = 0; i < m; ++i)
copy(result.begin(), result.begin() + n, result.begin() + n * i);
for (size_t i = 0; i < m; ++i) {
auto begin = result.begin();
for_each(begin + n * i, begin + n * (i+1), [&](string &s) {
s += keyboard[d - '0'][i];
});
}
}
return result;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item 无
\myenddot
================================================
FILE: C++/chapDFS.tex
================================================
\chapter{深度优先搜索}
\section{Palindrome Partitioning} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:palindrome-partitioning}
\subsubsection{描述}
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
For example, given \code{s = "aab"},
Return
\begin{Code}
[
["aa","b"],
["a","a","b"]
]
\end{Code}
\subsubsection{分析}
在每一步都可以判断中间结果是否为合法结果,用回溯法。
一个长度为n的字符串,有$n-1$个地方可以砍断,每个地方可断可不断,因此复杂度为$O(2^{n-1})$
\subsubsection{深搜1}
\begin{Code}
//LeetCode, Palindrome Partitioning
// 时间复杂度O(2^n),空间复杂度O(n)
class Solution {
public:
vector<vector<string>> partition(string s) {
vector<vector<string>> result;
vector<string> path; // 一个partition方案
dfs(s, path, result, 0, 1);
return result;
}
// prev 表示前一个隔板, start 表示当前隔板
void dfs(string &s, vector<string>& path,
vector<vector<string>> &result, size_t prev, size_t start) {
if (start == s.size()) { // 最后一个隔板
if (isPalindrome(s, prev, start - 1)) { // 必须使用
path.push_back(s.substr(prev, start - prev));
result.push_back(path);
path.pop_back();
}
return;
}
// 不断开
dfs(s, path, result, prev, start + 1);
// 如果[prev, start-1] 是回文,则可以断开,也可以不断开(上一行已经做了)
if (isPalindrome(s, prev, start - 1)) {
// 断开
path.push_back(s.substr(prev, start - prev));
dfs(s, path, result, start, start + 1);
path.pop_back();
}
}
bool isPalindrome(const string &s, int start, int end) {
while (start < end && s[start] == s[end]) {
++start;
--end;
}
return start >= end;
}
};
\end{Code}
\subsubsection{深搜2}
另一种写法,更加简洁。这种写法也在 Combination Sum, Combination Sum II 中出现过。
\begin{Code}
//LeetCode, Palindrome Partitioning
// 时间复杂度O(2^n),空间复杂度O(n)
class Solution {
public:
vector<vector<string>> partition(string s) {
vector<vector<string>> result;
vector<string> path; // 一个partition方案
DFS(s, path, result, 0);
return result;
}
// 搜索必须以s[start]开头的partition方案
void DFS(string &s, vector<string>& path,
vector<vector<string>> &result, int start) {
if (start == s.size()) {
result.push_back(path);
return;
}
for (int i = start; i < s.size(); i++) {
if (isPalindrome(s, start, i)) { // 从i位置砍一刀
path.push_back(s.substr(start, i - start + 1));
DFS(s, path, result, i + 1); // 继续往下砍
path.pop_back(); // 撤销上上行
}
}
}
bool isPalindrome(const string &s, int start, int end) {
while (start < end && s[start] == s[end]) {
++start;
--end;
}
return start >= end;
}
};
\end{Code}
\subsubsection{动规}
\begin{Code}
// LeetCode, Palindrome Partitioning
// 动规,时间复杂度O(n^2),空间复杂度O(1)
class Solution {
public:
vector<vector<string> > partition(string s) {
const int n = s.size();
bool p[n][n]; // whether s[i,j] is palindrome
fill_n(&p[0][0], n * n, false);
for (int i = n - 1; i >= 0; --i)
for (int j = i; j < n; ++j)
p[i][j] = s[i] == s[j] && ((j - i < 2) || p[i + 1][j - 1]);
vector<vector<string> > sub_palins[n]; // sub palindromes of s[0,i]
for (int i = n - 1; i >= 0; --i) {
for (int j = i; j < n; ++j)
if (p[i][j]) {
const string palindrome = s.substr(i, j - i + 1);
if (j + 1 < n) {
for (auto v : sub_palins[j + 1]) {
v.insert(v.begin(), palindrome);
sub_palins[i].push_back(v);
}
} else {
sub_palins[i].push_back(vector<string> { palindrome });
}
}
}
return sub_palins[0];
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Palindrome Partitioning II,见 \S \ref{sec:palindrome-partitioning-ii}
\myenddot
\section{Unique Paths} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:unique-paths}
\subsubsection{描述}
A robot is located at the top-left corner of a $m \times n$ grid (marked 'Start' in the diagram below).
The 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).
How many possible unique paths are there?
\begin{center}
\includegraphics[width=200pt]{robot-maze.png}\\
\figcaption{Above is a $3 \times 7$ grid. How many possible unique paths are there?}\label{fig:unique-paths}
\end{center}
\textbf{Note}: $m$ and $n$ will be at most 100.
\subsection{深搜}
深搜,小集合可以过,大集合会超时
\subsubsection{代码}
\begin{Code}
// LeetCode, Unique Paths
// 深搜,小集合可以过,大集合会超时
// 时间复杂度O(n^4),空间复杂度O(n)
class Solution {
public:
int uniquePaths(int m, int n) {
if (m < 1 || n < 1) return 0; // 终止条件
if (m == 1 && n == 1) return 1; // 收敛条件
return uniquePaths(m - 1, n) + uniquePaths(m, n - 1);
}
};
\end{Code}
\subsection{备忘录法}
给前面的深搜,加个缓存,就可以过大集合了。即备忘录法。
\subsubsection{代码}
\begin{Code}
// LeetCode, Unique Paths
// 深搜 + 缓存,即备忘录法
// 时间复杂度O(n^2),空间复杂度O(n^2)
class Solution {
public:
int uniquePaths(int m, int n) {
// f[x][y] 表示 从(0,0)到(x,y)的路径条数
f = vector<vector<int> >(m, vector<int>(n, 0));
f[0][0] = 1;
return dfs(m - 1, n - 1);
}
private:
vector<vector<int> > f; // 缓存
int dfs(int x, int y) {
if (x < 0 || y < 0) return 0; // 数据非法,终止条件
if (x == 0 && y == 0) return f[0][0]; // 回到起点,收敛条件
if (f[x][y] > 0) {
return f[x][y];
} else {
return f[x][y] = dfs(x - 1, y) + dfs(x, y - 1);
}
}
};
\end{Code}
\subsection{动规}
既然可以用备忘录法自顶向下解决,也一定可以用动规自底向上解决。
设状态为\fn{f[i][j]},表示从起点$(1,1)$到达$(i,j)$的路线条数,则状态转移方程为:
\begin{Code}
f[i][j]=f[i-1][j]+f[i][j-1]
\end{Code}
\subsubsection{代码}
\begin{Code}
// LeetCode, Unique Paths
// 动规,滚动数组
// 时间复杂度O(n^2),空间复杂度O(n)
class Solution {
public:
int uniquePaths(int m, int n) {
vector<int> f(n, 0);
f[0] = 1;
for (int i = 0; i < m; i++) {
for (int j = 1; j < n; j++) {
// 左边的f[j],表示更新后的f[j],与公式中的f[i][j]对应
// 右边的f[j],表示老的f[j],与公式中的f[i-1][j]对应
f[j] = f[j] + f[j - 1];
}
}
return f[n - 1];
}
};
\end{Code}
\subsection{数学公式}
一个$m$行,$n$列的矩阵,机器人从左上走到右下总共需要的步数是$m+n-2$,其中向下走的步数是$m-1$,因此问题变成了在$m+n-2$个操作中,选择$m–1$个时间点向下走,选择方式有多少种。即 $C_{m+n-2}^{m-1}$ 。
\subsubsection{代码}
\begin{Code}
// LeetCode, Unique Paths
// 数学公式
class Solution {
public:
typedef long long int64_t;
// 求阶乘, n!/(start-1)!,即 n*(n-1)...start,要求 n >= 1
static int64_t factor(int n, int start = 1) {
int64_t ret = 1;
for(int i = start; i <= n; ++i)
ret *= i;
return ret;
}
// 求组合数 C_n^k
static int64_t combination(int n, int k) {
// 常数优化
if (k == 0) return 1;
if (k == 1) return n;
int64_t ret = factor(n, k+1);
ret /= factor(n - k);
return ret;
}
int uniquePaths(int m, int n) {
// max 可以防止n和k差距过大,从而防止combination()溢出
return combination(m+n-2, max(m-1, n-1));
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Unique Paths II,见 \S \ref{sec:unique-paths-ii}
\item Minimum Path Sum, 见 \S \ref{sec:minimum-path-sum}
\myenddot
\section{Unique Paths II} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:unique-paths-ii}
\subsubsection{描述}
Follow up for "Unique Paths":
Now consider if some obstacles are added to the grids. How many unique paths would there be?
An obstacle and empty space is marked as 1 and 0 respectively in the grid.
For example,
There is one obstacle in the middle of a $3 \times 3$ grid as illustrated below.
\begin{Code}
[
[0,0,0],
[0,1,0],
[0,0,0]
]
\end{Code}
The total number of unique paths is 2.
Note: $m$ and $n$ will be at most 100.
\subsection{备忘录法}
在上一题的基础上改一下即可。相比动规,简单得多。
\subsubsection{代码}
\begin{Code}
// LeetCode, Unique Paths II
// 深搜 + 缓存,即备忘录法
class Solution {
public:
int uniquePathsWithObstacles(const vector<vector<int> >& obstacleGrid) {
const int m = obstacleGrid.size();
const int n = obstacleGrid[0].size();
if (obstacleGrid[0][0] || obstacleGrid[m - 1][n - 1]) return 0;
f = vector<vector<int> >(m, vector<int>(n, 0));
f[0][0] = obstacleGrid[0][0] ? 0 : 1;
return dfs(obstacleGrid, m - 1, n - 1);
}
private:
vector<vector<int> > f; // 缓存
// @return 从 (0, 0) 到 (x, y) 的路径总数
int dfs(const vector<vector<int> >& obstacleGrid,
int x, int y) {
if (x < 0 || y < 0) return 0; // 数据非法,终止条件
// (x,y)是障碍
if (obstacleGrid[x][y]) return 0;
if (x == 0 and y == 0) return f[0][0]; // 回到起点,收敛条件
if (f[x][y] > 0) {
return f[x][y];
} else {
return f[x][y] = dfs(obstacleGrid, x - 1, y) +
dfs(obstacleGrid, x, y - 1);
}
}
};
\end{Code}
\subsection{动规}
与上一题类似,但要特别注意第一列的障碍。在上一题中,第一列全部是1,但是在这一题中不同,第一列如果某一行有障碍物,那么后面的行全为0。
\subsubsection{代码}
\begin{Code}
// LeetCode, Unique Paths II
// 动规,滚动数组
// 时间复杂度O(n^2),空间复杂度O(n)
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {
const int m = obstacleGrid.size();
const int n = obstacleGrid[0].size();
if (obstacleGrid[0][0] || obstacleGrid[m-1][n-1]) return 0;
vector<int> f(n, 0);
f[0] = obstacleGrid[0][0] ? 0 : 1;
for (int i = 0; i < m; i++) {
f[0] = f[0] == 0 ? 0 : (obstacleGrid[i][0] ? 0 : 1);
for (int j = 1; j < n; j++)
f[j] = obstacleGrid[i][j] ? 0 : (f[j] + f[j - 1]);
}
return f[n - 1];
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Unique Paths,见 \S \ref{sec:unique-paths}
\item Minimum Path Sum, 见 \S \ref{sec:minimum-path-sum}
\myenddot
\section{N-Queens} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:n-queens}
\subsubsection{描述}
The \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.
\begin{center}
\includegraphics{8-queens.png}\\
\figcaption{Eight Queens}\label{fig:8-queens}
\end{center}
Given an integer $n$, return all distinct solutions to the n-queens puzzle.
Each 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.
For example,
There exist two distinct solutions to the 4-queens puzzle:
\begin{Code}
[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
\end{Code}
\subsubsection{分析}
经典的深搜题。
设置一个数组 \fn{vector<int> C(n, 0)}, \fn{C[i]} 表示第i行皇后所在的列编号,即在位置 (i, C[i]) 上放了一个皇后,这样用一个一维数组,就能记录整个棋盘。
\subsubsection{代码1}
\begin{Code}
// LeetCode, N-Queens
// 深搜+剪枝
// 时间复杂度O(n!*n),空间复杂度O(n)
class Solution {
public:
vector<vector<string> > solveNQueens(int n) {
vector<vector<string> > result;
vector<int> C(n, -1); // C[i]表示第i行皇后所在的列编号
dfs(C, result, 0);
return result;
}
private:
void dfs(vector<int> &C, vector<vector<string> > &result, int row) {
const int N = C.size();
if (row == N) { // 终止条件,也是收敛条件,意味着找到了一个可行解
vector<string> solution;
for (int i = 0; i < N; ++i) {
string s(N, '.');
for (int j = 0; j < N; ++j) {
if (j == C[i]) s[j] = 'Q';
}
solution.push_back(s);
}
result.push_back(solution);
return;
}
for (int j = 0; j < N; ++j) { // 扩展状态,一列一列的试
const bool ok = isValid(C, row, j);
if (!ok) continue; // 剪枝,如果非法,继续尝试下一列
// 执行扩展动作
C[row] = j;
dfs(C, result, row + 1);
// 撤销动作
// C[row] = -1;
}
}
/**
* 能否在 (row, col) 位置放一个皇后.
*
* @param C 棋局
* @param row 当前正在处理的行,前面的行都已经放了皇后了
* @param col 当前列
* @return 能否放一个皇后
*/
bool isValid(const vector<int> &C, int row, int col) {
for (int i = 0; i < row; ++i) {
// 在同一列
if (C[i] == col) return false;
// 在同一对角线上
if (abs(i - row) == abs(C[i] - col)) return false;
}
return true;
}
};
\end{Code}
\subsubsection{代码2}
\begin{Code}
// LeetCode, N-Queens
// 深搜+剪枝
// 时间复杂度O(n!),空间复杂度O(n)
class Solution {
public:
vector<vector<string> > solveNQueens(int n) {
this->columns = vector<bool>(n, false);
this->main_diag = vector<bool>(2 * n - 1, false);
this->anti_diag = vector<bool>(2 * n - 1, false);
vector<vector<string> > result;
vector<int> C(n, -1); // C[i]表示第i行皇后所在的列编号
dfs(C, result, 0);
return result;
}
private:
// 这三个变量用于剪枝
vector<bool> columns; // 表示已经放置的皇后占据了哪些列
vector<bool> main_diag; // 占据了哪些主对角线
vector<bool> anti_diag; // 占据了哪些副对角线
void dfs(vector<int> &C, vector<vector<string> > &result, int row) {
const int N = C.size();
if (row == N) { // 终止条件,也是收敛条件,意味着找到了一个可行解
vector<string> solution;
for (int i = 0; i < N; ++i) {
string s(N, '.');
for (int j = 0; j < N; ++j) {
if (j == C[i]) s[j] = 'Q';
}
solution.push_back(s);
}
result.push_back(solution);
return;
}
for (int j = 0; j < N; ++j) { // 扩展状态,一列一列的试
const bool ok = !columns[j] && !main_diag[row - j + N - 1] &&
!anti_diag[row + j];
if (!ok) continue; // 剪枝,如果非法,继续尝试下一列
// 执行扩展动作
C[row] = j;
columns[j] = main_diag[row - j + N - 1] = anti_diag[row + j] = true;
dfs(C, result, row + 1);
// 撤销动作
// C[row] = -1;
columns[j] = main_diag[row - j + N - 1] = anti_diag[row + j] = false;
}
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item N-Queens II,见 \S \ref{sec:n-queens-ii}
\myenddot
\section{N-Queens II} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:n-queens-ii}
\subsubsection{描述}
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
\subsubsection{分析}
只需要输出解的个数,不需要输出所有解,代码要比上一题简化很多。设一个全局计数器,每找到一个解就增1。
\subsubsection{代码1}
\begin{Code}
// LeetCode, N-Queens II
// 深搜+剪枝
// 时间复杂度O(n!*n),空间复杂度O(n)
class Solution {
public:
int totalNQueens(int n) {
this->count = 0;
vector<int> C(n, 0); // C[i]表示第i行皇后所在的列编号
dfs(C, 0);
return this->count;
}
private:
int count; // 解的个数
void dfs(vector<int> &C, int row) {
const int N = C.size();
if (row == N) { // 终止条件,也是收敛条件,意味着找到了一个可行解
++this->count;
return;
}
for (int j = 0; j < N; ++j) { // 扩展状态,一列一列的试
const bool ok = isValid(C, row, j);
if (!ok) continue; // 剪枝:如果合法,继续递归
// 执行扩展动作
C[row] = j;
dfs(C, row + 1);
// 撤销动作
// C[row] = -1;
}
}
/**
* 能否在 (row, col) 位置放一个皇后.
*
* @param C 棋局
* @param row 当前正在处理的行,前面的行都已经放了皇后了
* @param col 当前列
* @return 能否放一个皇后
*/
bool isValid(const vector<int> &C, int row, int col) {
for (int i = 0; i < row; ++i) {
// 在同一列
if (C[i] == col) return false;
// 在同一对角线上
if (abs(i - row) == abs(C[i] - col)) return false;
}
return true;
}
};
\end{Code}
\subsubsection{代码2}
\begin{Code}
// LeetCode, N-Queens II
// 深搜+剪枝
// 时间复杂度O(n!),空间复杂度O(n)
class Solution {
public:
int totalNQueens(int n) {
this->count = 0;
this->columns = vector<bool>(n, false);
this->main_diag = vector<bool>(2 * n - 1, false);
this->anti_diag = vector<bool>(2 * n - 1, false);
vector<int> C(n, 0); // C[i]表示第i行皇后所在的列编号
dfs(C, 0);
return this->count;
}
private:
int count; // 解的个数
// 这三个变量用于剪枝
vector<bool> columns; // 表示已经放置的皇后占据了哪些列
vector<bool> main_diag; // 占据了哪些主对角线
vector<bool> anti_diag; // 占据了哪些副对角线
void dfs(vector<int> &C, int row) {
const int N = C.size();
if (row == N) { // 终止条件,也是收敛条件,意味着找到了一个可行解
++this->count;
return;
}
for (int j = 0; j < N; ++j) { // 扩展状态,一列一列的试
const bool ok = !columns[j] &&
!main_diag[row - j + N] &&
!anti_diag[row + j];
if (!ok) continue; // 剪枝:如果合法,继续递归
// 执行扩展动作
C[row] = j;
columns[j] = main_diag[row - j + N] =
anti_diag[row + j] = true;
dfs(C, row + 1);
// 撤销动作
// C[row] = -1;
columns[j] = main_diag[row - j + N] =
anti_diag[row + j] = false;
}
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item N-Queens,见 \S \ref{sec:n-queens}
\myenddot
\section{Restore IP Addresses} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:restore-ip-addresses}
\subsubsection{描述}
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
For example:
Given \code{"25525511135"},
return \code{["255.255.11.135", "255.255.111.35"]}. (Order does not matter)
\subsubsection{分析}
必须要走到底部才能判断解是否合法,深搜。
\subsubsection{代码}
\begin{Code}
// LeetCode, Restore IP Addresses
// 时间复杂度O(n^4),空间复杂度O(n)
class Solution {
public:
vector<string> restoreIpAddresses(const string& s) {
vector<string> result;
vector<string> ip; // 存放中间结果
dfs(s, ip, result, 0);
return result;
}
/**
* @brief 解析字符串
* @param[in] s 字符串,输入数据
* @param[out] ip 存放中间结果
* @param[out] result 存放所有可能的IP地址
* @param[in] start 当前正在处理的 index
* @return 无
*/
void dfs(string s, vector<string>& ip, vector<string> &result,
size_t start) {
if (ip.size() == 4 && start == s.size()) { // 找到一个合法解
result.push_back(ip[0] + '.' + ip[1] + '.' + ip[2] + '.' + ip[3]);
return;
}
if (s.size() - start > (4 - ip.size()) * 3)
return; // 剪枝
if (s.size() - start < (4 - ip.size()))
return; // 剪枝
int num = 0;
for (size_t i = start; i < start + 3; i++) {
num = num * 10 + (s[i] - '0');
if (num < 0 || num > 255) continue; // 剪枝
ip.push_back(s.substr(start, i - start + 1));
dfs(s, ip, result, i + 1);
ip.pop_back();
if (num == 0) break; // 不允许前缀0,但允许单个0
}
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item 无
\myenddot
\section{Combination Sum} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:combination-sum}
\subsubsection{描述}
Given a set of candidate numbers ($C$) and a target number ($T$), find all unique combinations in $C$ where the candidate numbers sums to $T$.
The same repeated number may be chosen from $C$ \emph{unlimited} number of times.
Note:
\begindot
\item All numbers (including target) will be positive integers.
\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$).
\item The solution set must not contain duplicate combinations.
\myenddot
For example, given candidate set \fn{2,3,6,7} and target \fn{7},
A solution set is:
\begin{Code}
[7]
[2, 2, 3]
\end{Code}
\subsubsection{分析}
无
\subsubsection{代码}
\begin{Code}
// LeetCode, Combination Sum
// 时间复杂度O(n!),空间复杂度O(n)
class Solution {
public:
vector<vector<int> > combinationSum(vector<int> &nums, int target) {
sort(nums.begin(), nums.end());
vector<vector<int> > result; // 最终结果
vector<int> path; // 中间结果
dfs(nums, path, result, target, 0);
return result;
}
private:
void dfs(vector<int>& nums, vector<int>& path, vector<vector<int> > &result,
int gap, int start) {
if (gap == 0) { // 找到一个合法解
result.push_back(path);
return;
}
for (size_t i = start; i < nums.size(); i++) { // 扩展状态
if (gap < nums[i]) return; // 剪枝
path.push_back(nums[i]); // 执行扩展动作
dfs(nums, path, result, gap - nums[i], i);
path.pop_back(); // 撤销动作
}
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Combination Sum II ,见 \S \ref{sec:combination-sum-ii}
\myenddot
\section{Combination Sum II} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:combination-sum-ii}
\subsubsection{描述}
Given a collection of candidate numbers ($C$) and a target number ($T$), find all unique combinations in $C$ where the candidate numbers sums to $T$.
Each number in $C$ may only be used \emph{once} in the combination.
Note:
\begindot
\item All numbers (including target) will be positive integers.
\item Elements in a combination ($a_1, a_2, ..., a_k$) must be in non-descending order. (ie, $a_1 > a_2 > ... > a_k$).
\item The solution set must not contain duplicate combinations.
\myenddot
For example, given candidate set \fn{10,1,2,7,6,1,5} and target \fn{8},
A solution set is:
\begin{Code}
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
\end{Code}
\subsubsection{分析}
无
\subsubsection{代码}
\begin{Code}
// LeetCode, Combination Sum II
// 时间复杂度O(n!),空间复杂度O(n)
class Solution {
public:
vector<vector<int> > combinationSum2(vector<int> &nums, int target) {
sort(nums.begin(), nums.end()); // 跟第 50 行配合,
// 确保每个元素最多只用一次
vector<vector<int> > result;
vector<int> path;
dfs(nums, path, result, target, 0);
return result;
}
private:
// 使用nums[start, nums.size())之间的元素,能找到的所有可行解
static void dfs(const vector<int> &nums, vector<int> &path,
vector<vector<int> > &result, int gap, int start) {
if (gap == 0) { // 找到一个合法解
result.push_back(path);
return;
}
int previous = -1;
for (size_t i = start; i < nums.size(); i++) {
// 如果上一轮循环已经使用了nums[i],则本次循环就不能再选nums[i],
// 确保nums[i]最多只用一次
if (previous == nums[i]) continue;
if (gap < nums[i]) return; // 剪枝
previous = nums[i];
path.push_back(nums[i]);
dfs(nums, path, result, gap - nums[i], i + 1);
path.pop_back(); // 恢复环境
}
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Combination Sum ,见 \S \ref{sec:combination-sum}
\myenddot
\section{Generate Parentheses } %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:generate-parentheses}
\subsubsection{描述}
Given $n$ pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given $n = 3$, a solution set is:
\begin{Code}
"((()))", "(()())", "(())()", "()(())", "()()()"
\end{Code}
\subsubsection{分析}
小括号串是一个递归结构,跟单链表、二叉树等递归结构一样,首先想到用递归。
一步步构造字符串。当左括号出现次数$<n$时,就可以放置新的左括号。当右括号出现次数小于左括号出现次数时,就可以放置新的右括号。
\subsubsection{代码1}
\begin{Code}
// LeetCode, Generate Parentheses
// 时间复杂度O(TODO),空间复杂度O(n)
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> result;
string path;
if (n > 0) generate(n, path, result, 0, 0);
return result;
}
// l 表示 ( 出现的次数, r 表示 ) 出现的次数
void generate(int n, string& path, vector<string> &result, int l, int r) {
if (l == n) {
string s(path);
result.push_back(s.append(n - r, ')'));
return;
}
path.push_back('(');
generate(n, path, result, l + 1, r);
path.pop_back();
if (l > r) {
path.push_back(')');
generate(n, path, result, l, r + 1);
path.pop_back();
}
}
};
\end{Code}
\subsubsection{代码2}
另一种递归写法,更加简洁。
\begin{Code}
// LeetCode, Generate Parentheses
// @author 连城 (http://weibo.com/lianchengzju)
class Solution {
public:
vector<string> generateParenthesis (int n) {
if (n == 0) return vector<string>(1, "");
if (n == 1) return vector<string> (1, "()");
vector<string> result;
for (int i = 0; i < n; ++i)
for (auto inner : generateParenthesis (i))
for (auto outer : generateParenthesis (n - 1 - i))
result.push_back ("(" + inner + ")" + outer);
return result;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Valid Parentheses, 见 \S \ref{sec:valid-parentheses}
\item Longest Valid Parentheses, 见 \S \ref{sec:longest-valid-parentheses}
\myenddot
\section{Sudoku Solver} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:sudoku-solver}
\subsubsection{描述}
Write a program to solve a Sudoku puzzle by filling the empty cells.
Empty cells are indicated by the character \fn{'.'}.
You may assume that there will be only one unique solution.
\begin{center}
\includegraphics[width=150pt]{sudoku.png}\\
\figcaption{A sudoku puzzle...}\label{fig:sudoku}
\end{center}
\begin{center}
\includegraphics[width=150pt]{sudoku-solution.png}\\
\figcaption{...and its solution numbers marked in red}\label{fig:sudoku-solution}
\end{center}
\subsubsection{分析}
无。
\subsubsection{代码}
\begin{Code}
// LeetCode, Sudoku Solver
// 时间复杂度O(9^4),空间复杂度O(1)
class Solution {
public:
bool solveSudoku(vector<vector<char> > &board) {
for (int i = 0; i < 9; ++i)
for (int j = 0; j < 9; ++j) {
if (board[i][j] == '.') {
for (int k = 0; k < 9; ++k) {
board[i][j] = '1' + k;
if (isValid(board, i, j) && solveSudoku(board))
return true;
board[i][j] = '.';
}
return false;
}
}
return true;
}
private:
// 检查 (x, y) 是否合法
bool isValid(const vector<vector<char> > &board, int x, int y) {
int i, j;
for (i = 0; i < 9; i++) // 检查 y 列
if (i != x && board[i][y] == board[x][y])
return false;
for (j = 0; j < 9; j++) // 检查 x 行
if (j != y && board[x][j] == board[x][y])
return false;
for (i = 3 * (x / 3); i < 3 * (x / 3 + 1); i++)
for (j = 3 * (y / 3); j < 3 * (y / 3 + 1); j++)
if ((i != x || j != y) && board[i][j] == board[x][y])
return false;
return true;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Valid Sudoku, 见 \S \ref{sec:valid-sudoku}
\myenddot
\section{Word Search} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:word-search}
\subsubsection{描述}
Given a 2D board and a word, find if the word exists in the grid.
The 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.
For example,
Given board =
\begin{Code}
[
["ABCE"],
["SFCS"],
["ADEE"]
]
\end{Code}
word = \fn{"ABCCED"}, -> returns \fn{true},\\
word = \fn{"SEE"}, -> returns \fn{true},\\
word = \fn{"ABCB"}, -> returns \fn{false}.
\subsubsection{分析}
无。
\subsubsection{代码}
\begin{Code}
// LeetCode, Word Search
// 深搜,递归
// 时间复杂度O(n^2*m^2),空间复杂度O(n^2)
class Solution {
public:
bool exist(const vector<vector<char> > &board, const string& word) {
const int m = board.size();
const int n = board[0].size();
vector<vector<bool> > visited(m, vector<bool>(n, false));
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
if (dfs(board, word, 0, i, j, visited))
return true;
return false;
}
private:
static bool dfs(const vector<vector<char> > &board, const string &word,
int index, int x, int y, vector<vector<bool> > &visited) {
if (index == word.size())
return true; // 收敛条件
if (x < 0 || y < 0 || x >= board.size() || y >= board[0].size())
return false; // 越界,终止条件
if (visited[x][y]) return false; // 已经访问过,剪枝
if (board[x][y] != word[index]) return false; // 不相等,剪枝
visited[x][y] = true;
bool ret = dfs(board, word, index + 1, x - 1, y, visited) || // 上
dfs(board, word, index + 1, x + 1, y, visited) || // 下
dfs(board, word, index + 1, x, y - 1, visited) || // 左
dfs(board, word, index + 1, x, y + 1, visited); // 右
visited[x][y] = false;
return ret;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item 无
\myenddot
\section{小结} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:dfs-template}
\subsection{适用场景}
\textbf{输入数据}:如果是递归数据结构,如单链表,二叉树,集合,则百分之百可以用深搜;如果是非递归数据结构,如一维数组,二维数组,字符串,图,则概率小一些。
\textbf{状态转换图}:树或者图。
\textbf{求解目标}:必须要走到最深(例如对于树,必须要走到叶子节点)才能得到一个解,这种情况适合用深搜。
\subsection{思考的步骤}
\begin{enumerate}
\item 是求路径条数,还是路径本身(或动作序列)?深搜最常见的三个问题,求可行解的总数,求一个可行解,求所有可行解。
\begin{enumerate}
\item 如果是路径条数,则不需要存储路径。
\item 如果是求路径本身,则要用一个数组\fn{path[]}存储路径。跟宽搜不同,宽搜虽然最终求的也是一条路径,但是需要存储扩展过程中的所有路径,在没找到答案之前所有路径都不能放弃;而深搜,在搜索过程中始终只有一条路径,因此用一个数组就足够了。
\end{enumerate}
\item 只要求一个解,还是要求所有解?如果只要求一个解,那找到一个就可以返回;如果要求所有解,找到了一个后,还要继续扩展,直到遍历完。广搜一般只要求一个解,因而不需要考虑这个问题(广搜当然也可以求所有解,这时需要扩展到所有叶子节点,相当于在内存中存储整个状态转换图,非常占内存,因此广搜不适合解这类问题)。
\item 如何表示状态?即一个状态需要存储哪些些必要的数据,才能够完整提供如何扩展到下一步状态的所有信息。跟广搜不同,深搜的惯用写法,不是把数据记录在状态\fn{struct}里,而是添加函数参数(有时为了节省递归堆栈,用全局变量),\fn{struct}里的字段与函数参数一一对应。
\item 如何扩展状态?这一步跟上一步相关。状态里记录的数据不同,扩展方法就不同。对于固定不变的数据结构(一般题目直接给出,作为输入数据),如二叉树,图等,扩展方法很简单,直接往下一层走,对于隐式图,要先在第1步里想清楚状态所带的数据,想清楚了这点,那如何扩展就很简单了。
\item 终止条件是什么?终止条件是指到了不能扩展的末端节点。对于树,是叶子节点,对于图或隐式图,是出度为0的节点。
\item {收敛条件是什么?收敛条件是指找到了一个合法解的时刻。如果是正向深搜(父状态处理完了才进行递归,即父状态不依赖子状态,递归语句一定是在最后,尾递归),则是指是否达到目标状态;如果是逆向深搜(处理父状态时需要先知道子状态的结果,此时递归语句不在最后),则是指是否到达初始状态。
由于很多时候终止条件和收敛条件是是合二为一的,因此很多人不区分这两种条件。仔细区分这两种条件,还是很有必要的。
为了判断是否到了收敛条件,要在函数接口里用一个参数记录当前的位置(或距离目标还有多远)。如果是求一个解,直接返回这个解;如果是求所有解,要在这里收集解,即把第一步中表示路径的数组\fn{path[]}复制到解集合里。}
\item 关于判重
\begin{enumerate}
\item 是否需要判重?如果状态转换图是一棵树,则不需要判重,因为在遍历过程中不可能重复;如果状态转换图是一个DAG,则需要判重。这一点跟BFS不一样,BFS的状态转换图总是DAG,必须要判重。
\item 怎样判重?跟广搜相同,见第 \S \ref{sec:bfs-template} 节。同时,DAG说明存在重叠子问题,此时可以用缓存加速,见第8步。
\end{enumerate}
\item 如何加速?
\begin{enumerate}
\item 剪枝。深搜一定要好好考虑怎么剪枝,成本小收益大,加几行代码,就能大大加速。这里没有通用方法,只能具体问题具体分析,要充分观察,充分利用各种信息来剪枝,在中间节点提前返回。
\item 缓存。
\begin{enumerate}
\item 前提条件:状态转换图是一个DAG。DAG=>存在重叠子问题=>子问题的解会被重复利用,用缓存自然会有加速效果。如果依赖关系是树状的(例如树,单链表等),没必要加缓存,因为子问题只会一层层往下,用一次就再也不会用到,加了缓存也没什么加速效果。
\item 具体实现:可以用数组或HashMap。维度简单的,用数组;维度复杂的,用HashMap,C++有\fn{map},C++ 11以后有\fn{unordered_map},比\fn{map}快。
\end{enumerate}
\end{enumerate}
\end{enumerate}
拿到一个题目,当感觉它适合用深搜解决时,在心里面把上面8个问题默默回答一遍,代码基本上就能写出来了。对于树,不需要回答第5和第8个问题。如果读者对上面的经验总结看不懂或感觉“不实用”,很正常,因为这些经验总结是我做了很多题目后总结出来的,从思维的发展过程看,“经验总结”要晚于感性认识,所以这时候建议读者先做做前面的题目,积累一定的感性认识后,再回过头来看这一节的总结,一定会有共鸣。
\subsection{代码模板}
\begin{Codex}[label=dfs_template.cpp]
/**
* dfs模板.
* @param[in] input 输入数据指针
* @param[out] path 当前路径,也是中间结果
* @param[out] result 存放最终结果
* @param[inout] cur or gap 标记当前位置或距离目标的距离
* @return 路径长度,如果是求路径本身,则不需要返回长度
*/
void dfs(type &input, type &path, type &result, int cur or gap) {
if (数据非法) return 0; // 终止条件
if (cur == input.size()) { // 收敛条件
// if (gap == 0) {
将path放入result
}
if (可以剪枝) return;
for(...) { // 执行所有可能的扩展动作
执行动作,修改path
dfs(input, step + 1 or gap--, result);
恢复path
}
}
\end{Codex}
\subsection{深搜与回溯法的区别}
深搜(Depth-first search, DFS)的定义见\myurl{http://en.wikipedia.org/wiki/Depth_first_search},回溯法(backtracking)的定义见\myurl{http://en.wikipedia.org/wiki/Backtracking}
\textbf{回溯法 = 深搜 + 剪枝}。一般大家用深搜时,或多或少会剪枝,因此深搜与回溯法没有什么不同,可以在它们之间画上一个等号。本书同时使用深搜和回溯法两个术语,但读者可以认为二者等价。
深搜一般用递归(recursion)来实现,这样比较简洁。
深搜能够在候选答案生成到一半时,就进行判断,抛弃不满足要求的答案,所以深搜比暴力搜索法要快。
\subsection{深搜与递归的区别}
\label{sec:dfs-vs-recursion}
深搜经常用递归(recursion)来实现,二者常常同时出现,导致很多人误以为他俩是一个东西。
深搜,是逻辑意义上的算法,递归,是一种物理意义上的实现,它和迭代(iteration)是对应的。深搜,可以用递归来实现,也可以用栈来实现;而递归,一般总是用来实现深搜。可以说,\textbf{递归一定是深搜,深搜不一定用递归}。
递归有两种加速策略,一种是\textbf{剪枝(prunning)},对中间结果进行判断,提前返回;一种是\textbf{缓存},缓存中间结果,防止重复计算,用空间换时间。
其实,递归+缓存,就是 memoization。所谓\textbf{memoization}(翻译为备忘录法,见第 \S \ref{sec:dp-vs-memoization}节),就是"top-down with cache"(自顶向下+缓存),它是Donald Michie 在1968年创造的术语,表示一种优化技术,在top-down 形式的程序中,使用缓存来避免重复计算,从而达到加速的目的。
\textbf{memoization 不一定用递归},就像深搜不一定用递归一样,可以在迭代(iterative)中使用 memoization 。\textbf{递归也不一定用 memoization},可以用memoization来加速,但不是必须的。只有当递归使用了缓存,它才是 memoization 。
既然递归一定是深搜,为什么很多书籍都同时使用这两个术语呢?在递归味道更浓的地方,一般用递归这个术语,在深搜更浓的场景下,用深搜这个术语,读者心里要弄清楚他俩大部分时候是一回事。在单链表、二叉树等递归数据结构上,递归的味道更浓,这时用递归这个术语;在图、隐式图等数据结构上,深搜的味道更浓,这时用深搜这个术语。
================================================
FILE: C++/chapDivideAndConquer.tex
================================================
\chapter{分治法}
\section{Pow(x,n)} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:pow}
\subsubsection{描述}
Implement pow(x, n).
\subsubsection{分析}
二分法,$x^n = x^{n/2} \times x^{n/2} \times x^{n\%2}$
\subsubsection{代码}
\begin{Code}
//LeetCode, Pow(x, n)
// 二分法,$x^n = x^{n/2} * x^{n/2} * x^{n\%2}$
// 时间复杂度O(logn),空间复杂度O(1)
class Solution {
public:
double myPow(double x, int n) {
if (n < 0) return 1.0 / power(x, -n);
else return power(x, n);
}
private:
double power(double x, int n) {
if (n == 0) return 1;
double v = power(x, n / 2);
if (n % 2 == 0) return v * v;
else return v * v * x;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Sqrt(x),见 \S \ref{sec:sqrt}
\myenddot
\section{Sqrt(x)} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:sqrt}
\subsubsection{描述}
Implement int \fn{sqrt(int x)}.
Compute and return the square root of \fn{x}.
\subsubsection{分析}
二分查找
\subsubsection{代码}
\begin{Code}
// LeetCode, Sqrt(x)
// 二分查找
// 时间复杂度O(logn),空间复杂度O(1)
class Solution {
public:
int mySqrt(int x) {
int left = 1, right = x / 2;
int last_mid; // 记录最近一次mid
if (x < 2) return x;
while(left <= right) {
const int mid = left + (right - left) / 2;
if(x / mid > mid) { // 不要用 x > mid * mid,会溢出
left = mid + 1;
last_mid = mid;
} else if(x / mid < mid) {
right = mid - 1;
} else {
return mid;
}
}
return last_mid;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Pow(x),见 \S \ref{sec:pow}
\myenddot
================================================
FILE: C++/chapDynamicProgramming.tex
================================================
\chapter{动态规划}
\section{Triangle} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:triangle}
\subsubsection{描述}
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
For example, given the following triangle
\begin{Code}
[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
\end{Code}
The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).
Note: 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.
\subsubsection{分析}
设状态为$f(i, j)$,表示从从位置$(i,j)$出发,路径的最小和,则状态转移方程为
$$
f(i,j)=\min\left\{f(i+1,j),f(i+1,j+1)\right\}+(i,j)
$$
\subsubsection{代码}
\begin{Code}
// LeetCode, Triangle
// 时间复杂度O(n^2),空间复杂度O(1)
class Solution {
public:
int minimumTotal (vector<vector<int>>& triangle) {
for (int i = triangle.size() - 2; i >= 0; --i)
for (int j = 0; j < i + 1; ++j)
triangle[i][j] += min(triangle[i + 1][j],
triangle[i + 1][j + 1]);
return triangle [0][0];
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item 无
\myenddot
\section{Maximum Subarray} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:maximum-subarray}
\subsubsection{描述}
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array \code{[−2,1,−3,4,−1,2,1,−5,4]},
the contiguous subarray \code{[4,−1,2,1]} has the largest \code{sum = 6}.
\subsubsection{分析}
最大连续子序列和,非常经典的题。
当我们从头到尾遍历这个数组的时候,对于数组里的一个整数,它有几种选择呢?它只有两种选择: 1、加入之前的SubArray;2. 自己另起一个SubArray。那什么时候会出现这两种情况呢?
如果之前SubArray的总体和大于0的话,我们认为其对后续结果是有贡献的。这种情况下我们选择加入之前的SubArray
如果之前SubArray的总体和为0或者小于0的话,我们认为其对后续结果是没有贡献,甚至是有害的(小于0时)。这种情况下我们选择以这个数字开始,另起一个SubArray。
设状态为\fn{f[j]},表示以\fn{S[j]}结尾的最大连续子序列和,则状态转移方程如下:
\begin{eqnarray}
f[j] &=& \max\left\{f[j-1]+S[j],S[j]\right\}, \text{ 其中 }1 \leq j \leq n \nonumber \\
target &=& \max\left\{f[j]\right\}, \text{ 其中 }1 \leq j \leq n \nonumber
\end{eqnarray}
解释如下:
\begindot
\item 情况一,S[j]不独立,与前面的某些数组成一个连续子序列,则最大连续子序列和为$f[j-1]+S[j]$。
\item 情况二,S[j]独立划分成为一段,即连续子序列仅包含一个数S[j],则最大连续子序列和为$S[j]$。
\myenddot
其他思路:
\begindot
\item 思路2:直接在i到j之间暴力枚举,复杂度是$O(n^3)$
\item 思路3:处理后枚举,连续子序列的和等于两个前缀和之差,复杂度$O(n^2)$。
\item 思路4:分治法,把序列分为两段,分别求最大连续子序列和,然后归并,复杂度$O(n\log n)$
\item 思路5:把思路2$O(n^2)$的代码稍作处理,得到$O(n)$的算法
\item 思路6:当成M=1的最大M子段和
\myenddot
\subsubsection{动规}
\begin{Code}
// LeetCode, Maximum Subarray
// 时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int result = INT_MIN, f = 0;
for (int i = 0; i < nums.size(); ++i) {
f = max(f + nums[i], nums[i]);
result = max(result, f);
}
return result;
}
};
\end{Code}
\subsubsection{思路5}
\begin{Code}
// LeetCode, Maximum Subarray
// 时间复杂度O(n),空间复杂度O(n)
class Solution {
public:
int maxSubArray(vector<int>& A) {
return mcss(A.begin(), A.end());
}
private:
// 思路5,求最大连续子序列和
template <typename Iter>
static int mcss(Iter begin, Iter end) {
int result, cur_min;
const int n = distance(begin, end);
int *sum = new int[n + 1]; // 前n项和
sum[0] = 0;
result = INT_MIN;
cur_min = sum[0];
for (int i = 1; i <= n; i++) {
sum[i] = sum[i - 1] + *(begin + i - 1);
}
for (int i = 1; i <= n; i++) {
result = max(result, sum[i] - cur_min);
cur_min = min(cur_min, sum[i]);
}
delete[] sum;
return result;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Binary Tree Maximum Path Sum,见 \S \ref{sec:binary-tree-maximum-path-sum}
\myenddot
\section{Palindrome Partitioning II} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:palindrome-partitioning-ii}
\subsubsection{描述}
Given a string s, partition s such that every substring of the partition is a palindrome.
Return the minimum cuts needed for a palindrome partitioning of s.
For example, given \code{s = "aab"},
Return 1 since the palindrome partitioning \code{["aa","b"]} could be produced using 1 cut.
\subsubsection{分析}
定义状态\fn{f(i,j)}表示区间\fn{[i,j]}之间最小的cut数,则状态转移方程为
$$
f(i,j)=\min\left\{f(i,k)+f(k+1,j)\right\}, i \leq k \leq j, 0 \leq i \leq j<n
$$
这是一个二维函数,实际写代码比较麻烦。
所以要转换成一维DP。如果每次,从i往右扫描,每找到一个回文就算一次DP的话,就可以转换为\code{f(i)=区间[i, n-1]之间最小的cut数},n为字符串长度,则状态转移方程为
$$
f(i)=\min\left\{f(j+1)+1\right\}, i \leq j<n
$$
一个问题出现了,就是如何判断\fn{[i,j]}是否是回文?每次都从i到j比较一遍?太浪费了,这里也是一个DP问题。
定义状态\fn{P[i][j] = true if [i,j]为回文},那么
\begin{Code}
P[i][j] = str[i] == str[j] && P[i+1][j-1]
\end{Code}
\subsubsection{代码}
\begin{Code}
// LeetCode, Palindrome Partitioning II
// 时间复杂度O(n^2),空间复杂度O(n^2)
class Solution {
public:
int minCut(const string& s) {
const int n = s.size();
int f[n+1];
bool p[n][n];
fill_n(&p[0][0], n * n, false);
//the worst case is cutting by each char
for (int i = 0; i <= n; i++)
f[i] = n - 1 - i; // 最后一个f[n]=-1
for (int i = n - 1; i >= 0; i--) {
for (int j = i; j < n; j++) {
if (s[i] == s[j] && (j - i < 2 || p[i + 1][j - 1])) {
p[i][j] = true;
f[i] = min(f[i], f[j + 1] + 1);
}
}
}
return f[0];
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Palindrome Partitioning,见 \S \ref{sec:palindrome-partitioning}
\myenddot
\section{Maximal Rectangle} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:maximal-rectangle}
\subsubsection{描述}
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.
\subsubsection{分析}
无
\subsubsection{代码}
\begin{Code}
// LeetCode, Maximal Rectangle
// 时间复杂度O(n^2),空间复杂度O(n)
class Solution {
public:
int maximalRectangle(vector<vector<char> > &matrix) {
if (matrix.empty()) return 0;
const int m = matrix.size();
const int n = matrix[0].size();
vector<int> H(n, 0);
vector<int> L(n, 0);
vector<int> R(n, n);
int ret = 0;
for (int i = 0; i < m; ++i) {
int left = 0, right = n;
// calculate L(i, j) from left to right
for (int j = 0; j < n; ++j) {
if (matrix[i][j] == '1') {
++H[j];
L[j] = max(L[j], left);
} else {
left = j+1;
H[j] = 0; L[j] = 0; R[j] = n;
}
}
// calculate R(i, j) from right to left
for (int j = n-1; j >= 0; --j) {
if (matrix[i][j] == '1') {
R[j] = min(R[j], right);
ret = max(ret, H[j]*(R[j]-L[j]));
} else {
right = j;
}
}
}
return ret;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item 无
\myenddot
\section{Best Time to Buy and Sell Stock III} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:best-time-to-buy-and-sell-stock-iii}
\subsubsection{描述}
Say you have an array for which the i-th element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most two transactions.
Note: You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
\subsubsection{分析}
设状态$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$。
允许在一天内买进又卖出,相当于不交易,因为题目的规定是最多两次,而不是一定要两次。
将原数组变成差分数组,本题也可以看做是最大$m$子段和,$m=2$,参考代码:\myurl{https://gist.github.com/soulmachine/5906637}
\subsubsection{代码}
\begin{Code}
// LeetCode, Best Time to Buy and Sell Stock III
// 时间复杂度O(n),空间复杂度O(n)
class Solution {
public:
int maxProfit(vector<int>& prices) {
if (prices.size() < 2) return 0;
const int n = prices.size();
vector<int> f(n, 0);
vector<int> g(n, 0);
for (int i = 1, valley = prices[0]; i < n; ++i) {
valley = min(valley, prices[i]);
f[i] = max(f[i - 1], prices[i] - valley);
}
for (int i = n - 2, peak = prices[n - 1]; i >= 0; --i) {
peak = max(peak, prices[i]);
g[i] = max(g[i], peak - prices[i]);
}
int max_profit = 0;
for (int i = 0; i < n; ++i)
max_profit = max(max_profit, f[i] + g[i]);
return max_profit;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Best Time to Buy and Sell Stock,见 \S \ref{sec:best-time-to-buy-and-sell-stock}
\item Best Time to Buy and Sell Stock II,见 \S \ref{sec:best-time-to-buy-and-sell-stock-ii}
\myenddot
\section{Interleaving String} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:interleaving-string}
\subsubsection{描述}
Given $s1, s2, s3$, find whether $s3$ is formed by the interleaving of $s1$ and $s2$.
For example, Given: \code{s1 = "aabcc", s2 = "dbbca"},
When \code{s3 = "aadbbcbcac"}, return true.
When \code{s3 = "aadbbbaccc"}, return false.
\subsubsection{分析}
设状态\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]}。因此状态转移方程如下:
\begin{Code}
f[i][j] = (s1[i - 1] == s3 [i + j - 1] && f[i - 1][j])
|| (s2[j - 1] == s3 [i + j - 1] && f[i][j - 1]);
\end{Code}
\subsubsection{递归}
\begin{Code}
// LeetCode, Interleaving String
// 递归,会超时,仅用来帮助理解
class Solution {
public:
bool isInterleave(const string& s1, const string& s2, const string& s3) {
if (s3.length() != s1.length() + s2.length())
return false;
return isInterleave(begin(s1), end(s1), begin(s2), end(s2),
begin(s3), end(s3));
}
template<typename InIt>
bool isInterleave(InIt first1, InIt last1, InIt first2, InIt last2,
InIt first3, InIt last3) {
if (first3 == last3)
return first1 == last1 && first2 == last2;
return (*first1 == *first3
&& isInterleave(next(first1), last1, first2, last2,
next(first3), last3))
|| (*first2 == *first3
&& isInterleave(first1, last1, next(first2), last2,
next(first3), last3));
}
};
\end{Code}
\subsubsection{动规}
\begin{Code}
// LeetCode, Interleaving String
// 二维动规,时间复杂度O(n^2),空间复杂度O(n^2)
class Solution {
public:
bool isInterleave(const string& s1, const string& s2, const string& s3) {
if (s3.length() != s1.length() + s2.length())
return false;
vector<vector<bool>> f(s1.length() + 1,
vector<bool>(s2.length() + 1, true));
for (size_t i = 1; i <= s1.length(); ++i)
f[i][0] = f[i - 1][0] && s1[i - 1] == s3[i - 1];
for (size_t i = 1; i <= s2.length(); ++i)
f[0][i] = f[0][i - 1] && s2[i - 1] == s3[i - 1];
for (size_t i = 1; i <= s1.length(); ++i)
for (size_t j = 1; j <= s2.length(); ++j)
f[i][j] = (s1[i - 1] == s3[i + j - 1] && f[i - 1][j])
|| (s2[j - 1] == s3[i + j - 1] && f[i][j - 1]);
return f[s1.length()][s2.length()];
}
};
\end{Code}
\subsubsection{动规+滚动数组}
\begin{Code}
// LeetCode, Interleaving String
// 二维动规+滚动数组,时间复杂度O(n^2),空间复杂度O(n)
class Solution {
public:
bool isInterleave(const string& s1, const string& s2, const string& s3) {
if (s1.length() + s2.length() != s3.length())
return false;
if (s1.length() < s2.length())
return isInterleave(s2, s1, s3);
vector<bool> f(s2.length() + 1, true);
for (size_t i = 1; i <= s2.length(); ++i)
f[i] = s2[i - 1] == s3[i - 1] && f[i - 1];
for (size_t i = 1; i <= s1.length(); ++i) {
f[0] = s1[i - 1] == s3[i - 1] && f[0];
for (size_t j = 1; j <= s2.length(); ++j)
f[j] = (s1[i - 1] == s3[i + j - 1] && f[j])
|| (s2[j - 1] == s3[i + j - 1] && f[j - 1]);
}
return f[s2.length()];
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item 无
\myenddot
\section{Scramble String} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:scramble-string}
\subsubsection{描述}
Given a string $s1$, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively.
Below is one possible representation of \code{s1 = "great"}:
\begin{Code}
great
/ \
gr eat
/ \ / \
g r e at
/ \
a t
\end{Code}
To scramble the string, we may choose any non-leaf node and swap its two children.
For example, if we choose the node \code{"gr"} and swap its two children, it produces a scrambled string \code{"rgeat"}.
\begin{Code}
rgeat
/ \
rg eat
/ \ / \
r g e at
/ \
a t
\end{Code}
We say that \code{"rgeat"} is a scrambled string of \code{"great"}.
Similarly, if we continue to swap the children of nodes \code{"eat"} and \code{"at"}, it produces a scrambled string \code{"rgtae"}.
\begin{Code}
rgtae
/ \
rg tae
/ \ / \
r g ta e
/ \
t a
\end{Code}
We say that \code{"rgtae"} is a scrambled string of \code{"great"}.
Given two strings $s1$ and $s2$ of the same length, determine if $s2$ is a scrambled string of $s1$.
\subsubsection{分析}
首先想到的是递归(即深搜),对两个string进行分割,然后比较四对字符串。代码虽然简单,但是复杂度比较高。有两种加速策略,一种是剪枝,提前返回;一种是加缓存,缓存中间结果,即memoization(翻译为记忆化搜索)。
剪枝可以五花八门,要充分观察,充分利用信息,找到能让节点提前返回的条件。例如,判断两个字符串是否互为scamble,至少要求每个字符在两个字符串中出现的次数要相等,如果不相等则返回false。
加缓存,可以用数组或HashMap。本题维数较高,用HashMap,\fn{map}和\fn{unordered_map}均可。
既然可以用记忆化搜索,这题也一定可以用动规。设状态为\fn{f[n][i][j]},表示长度为$n$,起点为\fn{s1[i]}和起点为\fn{s2[j]}两个字符串是否互为scramble,则状态转移方程为
\begin{Code}
f[n][i][j]} = (f[k][i][j] && f[n-k][i+k][j+k])
|| (f[k][i][j+n-k] && f[n-k][i+k][j])
\end{Code}
\subsubsection{递归}
\begin{Code}
// LeetCode, Scramble String
// 递归,会超时,仅用来帮助理解
// 时间复杂度O(n^6),空间复杂度O(1)
class Solution {
public:
bool isScramble(const string& s1, const string& s2) {
return isScramble(s1.begin(), s1.end(), s2.begin());
}
private:
typedef string::iterator Iterator;
bool isScramble(Iterator first1, Iterator last1, Iterator first2) {
auto length = distance(first1, last1);
auto last2 = next(first2, length);
if (length == 1) return *first1 == *first2;
for (int i = 1; i < length; ++i)
if ((isScramble(first1, first1 + i, first2)
&& isScramble(first1 + i, last1, first2 + i))
|| (isScramble(first1, first1 + i, last2 - i)
&& isScramble(first1 + i, last1, first2)))
return true;
return false;
}
};
\end{Code}
\subsubsection{动规}
\begin{Code}
// LeetCode, Scramble String
// 动规,时间复杂度O(n^3),空间复杂度O(n^3)
class Solution {
public:
bool isScramble(const string& s1, const string& s2) {
const int N = s1.size();
if (N != s2.size()) return false;
// f[n][i][j],表示长度为n,起点为s1[i]和
// 起点为s2[j]两个字符串是否互为scramble
bool f[N + 1][N][N];
fill_n(&f[0][0][0], (N + 1) * N * N, false);
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
f[1][i][j] = s1[i] == s2[j];
for (int n = 1; n <= N; ++n) {
for (int i = 0; i + n <= N; ++i) {
for (int j = 0; j + n <= N; ++j) {
for (int k = 1; k < n; ++k) {
if ((f[k][i][j] && f[n - k][i + k][j + k]) ||
(f[k][i][j + n - k] && f[n - k][i + k][j])) {
f[n][i][j] = true;
break;
}
}
}
}
}
return f[N][0][0];
}
};
\end{Code}
\subsubsection{递归+剪枝}
\begin{Code}
// LeetCode, Scramble String
// 递归+剪枝
// 时间复杂度O(n^6),空间复杂度O(1)
class Solution {
public:
bool isScramble(const string& s1, const string& s2) {
return isScramble(s1.begin(), s1.end(), s2.begin());
}
private:
typedef string::const_iterator Iterator;
bool isScramble(Iterator first1, Iterator last1, Iterator first2) {
auto length = distance(first1, last1);
auto last2 = next(first2, length);
if (length == 1) return *first1 == *first2;
// 剪枝,提前返回
int A[26]; // 每个字符的计数器
fill(A, A + 26, 0);
for(int i = 0; i < length; i++) A[*(first1+i)-'a']++;
for(int i = 0; i < length; i++) A[*(first2+i)-'a']--;
for(int i = 0; i < 26; i++) if (A[i] != 0) return false;
for (int i = 1; i < length; ++i)
if ((isScramble(first1, first1 + i, first2)
&& isScramble(first1 + i, last1, first2 + i))
|| (isScramble(first1, first1 + i, last2 - i)
&& isScramble(first1 + i, last1, first2)))
return true;
return false;
}
};
\end{Code}
\subsubsection{备忘录法}
\begin{Code}
// LeetCode, Scramble String
// 递归+map做cache
// 时间复杂度O(n^3),空间复杂度O(n^3), TLE
class Solution {
public:
bool isScramble(const string& s1, const string& s2) {
cache.clear();
return isScramble(s1.begin(), s1.end(), s2.begin());
}
private:
typedef string::const_iterator Iterator;
map<tuple<Iterator, Iterator, Iterator>, bool> cache;
bool isScramble(Iterator first1, Iterator last1, Iterator first2) {
auto length = distance(first1, last1);
auto last2 = next(first2, length);
if (length == 1) return *first1 == *first2;
for (int i = 1; i < length; ++i)
if ((getOrUpdate(first1, first1 + i, first2)
&& getOrUpdate(first1 + i, last1, first2 + i))
|| (getOrUpdate(first1, first1 + i, last2 - i)
&& getOrUpdate(first1 + i, last1, first2)))
return true;
return false;
}
bool getOrUpdate(Iterator first1, Iterator last1, Iterator first2) {
auto key = make_tuple(first1, last1, first2);
auto pos = cache.find(key);
return (pos != cache.end()) ?
pos->second : (cache[key] = isScramble(first1, last1, first2));
}
};
\end{Code}
\subsubsection{备忘录法}
\begin{Code}
typedef string::const_iterator Iterator;
typedef tuple<Iterator, Iterator, Iterator> Key;
// 定制一个哈希函数
namespace std {
template<> struct hash<Key> {
size_t operator()(const Key & x) const {
Iterator first1, last1, first2;
tie(first1, last1, first2) = x;
int result = *first1;
result = result * 31 + *last1;
result = result * 31 + *first2;
result = result * 31 + *(next(first2, distance(first1, last1)-1));
return result;
}
};
}
// LeetCode, Scramble String
// 递归+unordered_map做cache,比map快
// 时间复杂度O(n^3),空间复杂度O(n^3)
class Solution {
public:
unordered_map<Key, bool> cache;
bool isScramble(const string& s1, const string& s2) {
cache.clear();
return isScramble(s1.begin(), s1.end(), s2.begin());
}
bool isScramble(Iterator first1, Iterator last1, Iterator first2) {
auto length = distance(first1, last1);
auto last2 = next(first2, length);
if (length == 1)
return *first1 == *first2;
for (int i = 1; i < length; ++i)
if ((getOrUpdate(first1, first1 + i, first2)
&& getOrUpdate(first1 + i, last1, first2 + i))
|| (getOrUpdate(first1, first1 + i, last2 - i)
&& getOrUpdate(first1 + i, last1, first2)))
return true;
return false;
}
bool getOrUpdate(Iterator first1, Iterator last1, Iterator first2) {
auto key = make_tuple(first1, last1, first2);
auto pos = cache.find(key);
return (pos != cache.end()) ?
pos->second : (cache[key] = isScramble(first1, last1, first2));
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item 无
\myenddot
\section{Minimum Path Sum} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:minimum-path-sum}
\subsubsection{描述}
Given 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.
Note: You can only move either down or right at any point in time
\subsubsection{分析}
跟 Unique Paths (见 \S \ref{sec:unique-paths}) 很类似。
设状态为\fn{f[i][j]},表示从起点$(0,0)$到达$(i,j)$的最小路径和,则状态转移方程为:
\begin{Code}
f[i][j]=min(f[i-1][j], f[i][j-1])+grid[i][j]
\end{Code}
\subsubsection{备忘录法}
\begin{Code}
// LeetCode, Minimum Path Sum
// 备忘录法
class Solution {
public:
int minPathSum(vector<vector<int> > &grid) {
const int m = grid.size();
const int n = grid[0].size();
this->f = vector<vector<int> >(m, vector<int>(n, -1));
return dfs(grid, m-1, n-1);
}
private:
vector<vector<int> > f; // 缓存
int dfs(const vector<vector<int> > &grid, int x, int y) {
if (x < 0 || y < 0) return INT_MAX; // 越界,终止条件,注意,不是0
if (x == 0 && y == 0) return grid[0][0]; // 回到起点,收敛条件
return min(getOrUpdate(grid, x - 1, y),
getOrUpdate(grid, x, y - 1)) + grid[x][y];
}
int getOrUpdate(const vector<vector<int> > &grid, int x, int y) {
if (x < 0 || y < 0) return INT_MAX; // 越界,注意,不是0
if (f[x][y] >= 0) return f[x][y];
else return f[x][y] = dfs(grid, x, y);
}
};
\end{Code}
\subsubsection{动规}
\begin{Code}
// LeetCode, Minimum Path Sum
// 二维动规
class Solution {
public:
int minPathSum(vector<vector<int> > &grid) {
if (grid.size() == 0) return 0;
const int m = grid.size();
const int n = grid[0].size();
int f[m][n];
f[0][0] = grid[0][0];
for (int i = 1; i < m; i++) {
f[i][0] = f[i - 1][0] + grid[i][0];
}
for (int i = 1; i < n; i++) {
f[0][i] = f[0][i - 1] + grid[0][i];
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
f[i][j] = min(f[i - 1][j], f[i][j - 1]) + grid[i][j];
}
}
return f[m - 1][n - 1];
}
};
\end{Code}
\subsubsection{动规+滚动数组}
\begin{Code}
// LeetCode, Minimum Path Sum
// 二维动规+滚动数组
class Solution {
public:
int minPathSum(vector<vector<int> > &grid) {
const int m = grid.size();
const int n = grid[0].size();
int f[n];
fill(f, f+n, INT_MAX); // 初始值是 INT_MAX,因为后面用了min函数。
f[0] = 0;
for (int i = 0; i < m; i++) {
f[0] += grid[i][0];
for (int j = 1; j < n; j++) {
// 左边的f[j],表示更新后的f[j],与公式中的f[i[[j]对应
// 右边的f[j],表示老的f[j],与公式中的f[i-1][j]对应
f[j] = min(f[j - 1], f[j]) + grid[i][j];
}
}
return f[n - 1];
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Unique Paths, 见 \S \ref{sec:unique-paths}
\item Unique Paths II, 见 \S \ref{sec:unique-paths-ii}
\myenddot
\section{Edit Distance} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:edit-distance}
\subsubsection{描述}
Given 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.)
You have the following 3 operations permitted on a word:
\begindot
\item Insert a character
\item Delete a character
\item Replace a character
\myenddot
\subsubsection{分析}
设状态为\fn{f[i][j]},表示\fn{A[0,i]}和\fn{B[0,j]}之间的最小编辑距离。设\fn{A[0,i]}的形式是\fn{str1c},\fn{B[0,j]}的形式是\fn{str2d},
\begin{enumerate}
\item 如果\fn{c==d},则\fn{f[i][j]=f[i-1][j-1]};
\item 如果\fn{c!=d},
\begin{enumerate}
\item 如果将c替换成d,则\fn{f[i][j]=f[i-1][j-1]+1};
\item 如果在c后面添加一个d,则\fn{f[i][j]=f[i][j-1]+1};
\item 如果将c删除,则\fn{f[i][j]=f[i-1][j]+1};
\end{enumerate}
\end{enumerate}
\subsubsection{动规}
\begin{Code}
// LeetCode, Edit Distance
// 二维动规,时间复杂度O(n*m),空间复杂度O(n*m)
class Solution {
public:
int minDistance(const string &word1, const string &word2) {
const size_t n = word1.size();
const size_t m = word2.size();
// 长度为n的字符串,有n+1个隔板
int f[n + 1][m + 1];
for (size_t i = 0; i <= n; i++)
f[i][0] = i;
for (size_t j = 0; j <= m; j++)
f[0][j] = j;
for (size_t i = 1; i <= n; i++) {
for (size_t j = 1; j <= m; j++) {
if (word1[i - 1] == word2[j - 1])
f[i][j] = f[i - 1][j - 1];
else {
int mn = min(f[i - 1][j], f[i][j - 1]);
f[i][j] = 1 + min(f[i - 1][j - 1], mn);
}
}
}
return f[n][m];
}
};
\end{Code}
\subsubsection{动规+滚动数组}
\begin{Code}
// LeetCode, Edit Distance
// 二维动规+滚动数组
// 时间复杂度O(n*m),空间复杂度O(n)
class Solution {
public:
int minDistance(const string &word1, const string &word2) {
if (word1.length() < word2.length())
return minDistance(word2, word1);
int f[word2.length() + 1];
int upper_left = 0; // 额外用一个变量记录f[i-1][j-1]
for (size_t i = 0; i <= word2.size(); ++i)
f[i] = i;
for (size_t i = 1; i <= word1.size(); ++i) {
upper_left = f[0];
f[0] = i;
for (size_t j = 1; j <= word2.size(); ++j) {
int upper = f[j];
if (word1[i - 1] == word2[j - 1])
f[j] = upper_left;
else
f[j] = 1 + min(upper_left, min(f[j], f[j - 1]));
upper_left = upper;
}
}
return f[word2.length()];
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item 无
\myenddot
\section{Decode Ways} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:decode-ways}
\subsubsection{描述}
A message containing letters from \fn{A-Z} is being encoded to numbers using the following mapping:
\begin{Code}
'A' -> 1
'B' -> 2
...
'Z' -> 26
\end{Code}
Given an encoded message containing digits, determine the total number of ways to decode it.
For example,
Given encoded message \fn{"12"}, it could be decoded as \fn{"AB"} (1 2) or \fn{"L"} (12).
The number of ways decoding \fn{"12"} is 2.
\subsubsection{分析}
跟 Climbing Stairs (见 \S \ref{sec:climbing-stairs})很类似,不过多加一些判断逻辑。
\subsubsection{代码}
\begin{Code}
// LeetCode, Decode Ways
// 动规,时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
int numDecodings(const string &s) {
if (s.empty() || s[0] == '0') return 0;
int prev = 0;
int cur = 1;
// 长度为n的字符串,有 n+1个阶梯
for (size_t i = 1; i <= s.size(); ++i) {
if (s[i-1] == '0') cur = 0;
if (i < 2 || !(s[i - 2] == '1' ||
(s[i - 2] == '2' && s[i - 1] <= '6')))
prev = 0;
int tmp = cur;
cur = prev + cur;
prev = tmp;
}
return cur;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Climbing Stairs, 见 \S \ref{sec:climbing-stairs}
\myenddot
\section{Distinct Subsequences} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:distinct-subsequences}
\subsubsection{描述}
Given a string $S$ and a string $T$, count the number of distinct subsequences of $T$ in $S$.
A 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).
Here is an example:
$S$ = \fn{"rabbbit"}, $T$ = \fn{"rabbit"}
Return 3.
\subsubsection{分析}
设状态为$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)$。
\subsubsection{代码}
\begin{Code}
// LeetCode, Distinct Subsequences
// 二维动规+滚动数组
// 时间复杂度O(m*n),空间复杂度O(n)
class Solution {
public:
int numDistinct(const string &S, const string &T) {
vector<int> f(T.size() + 1);
f[0] = 1;
for (int i = 0; i < S.size(); ++i) {
for (int j = T.size() - 1; j >= 0; --j) {
f[j + 1] += S[i] == T[j] ? f[j] : 0;
}
}
return f[T.size()];
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item 无
\myenddot
\section{Word Break} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:word-break}
\subsubsection{描述}
Given 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.
For example, given \\
s = \fn{"leetcode"},\\
dict = \fn{["leet", "code"]}.
Return true because \fn{"leetcode"} can be segmented as \fn{"leet code"}.
\subsubsection{分析}
设状态为$f(i)$,表示\fn{s[0,i]}是否可以分词,则状态转移方程为
$$
f(i) = any\_of(f(j) \&\& s[j+1,i] \in dict), 0 \leq j < i
$$
\subsubsection{深搜}
\begin{Code}
// LeetCode, Word Break
// 深搜,超时
// 时间复杂度O(2^n),空间复杂度O(n)
class Solution {
public:
bool wordBreak(string s, unordered_set<string> &dict) {
return dfs(s, dict, 0, 0);
}
private:
static bool dfs(const string &s, unordered_set<string> &dict,
size_t start, size_t cur) {
if (cur == s.size()) {
return dict.find(s.substr(start, cur-start+1)) != dict.end();
}
if (dfs(s, dict, start, cur+1)) return true;
if (dict.find(s.substr(start, cur-start+1)) != dict.end())
if (dfs(s, dict, cur+1, cur+1)) return true;
return false;
}
};
\end{Code}
\subsubsection{动规}
\begin{Code}
// LeetCode, Word Break
// 动规,时间复杂度O(n^2),空间复杂度O(n)
class Solution {
public:
bool wordBreak(string s, unordered_set<string> &dict) {
// 长度为n的字符串有n+1个隔板
vector<bool> f(s.size() + 1, false);
f[0] = true; // 空字符串
for (int i = 1; i <= s.size(); ++i) {
for (int j = i - 1; j >= 0; --j) {
if (f[j] && dict.find(s.substr(j, i - j)) != dict.end()) {
f[i] = true;
break;
}
}
}
return f[s.size()];
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Word Break II, 见 \S \ref{sec:word-break-ii}
\myenddot
\section{Word Break II} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:word-break-ii}
\subsubsection{描述}
Given 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.
Return all such possible sentences.
For example, given \\
s = \fn{"catsanddog"}, \\
dict = \fn{["cat", "cats", "and", "sand", "dog"]}.
A solution is \fn{["cats and dog", "cat sand dog"]}.
\subsubsection{分析}
在上一题的基础上,要返回解本身。
\subsubsection{代码}
\begin{Code}
// LeetCode, Word Break II
// 动规,时间复杂度O(n^2),空间复杂度O(n^2)
class Solution {
public:
vector<string> wordBreak(string s, unordered_set<string> &dict) {
// 长度为n的字符串有n+1个隔板
vector<bool> f(s.length() + 1, false);
// prev[i][j]为true,表示s[j, i)是一个合法单词,可以从j处切开
// 第一行未用
vector<vector<bool> > prev(s.length() + 1, vector<bool>(s.length()));
f[0] = true;
for (size_t i = 1; i <= s.length(); ++i) {
for (int j = i - 1; j >= 0; --j) {
if (f[j] && dict.find(s.substr(j, i - j)) != dict.end()) {
f[i] = true;
prev[i][j] = true;
}
}
}
vector<string> result;
vector<string> path;
gen_path(s, prev, s.length(), path, result);
return result;
}
private:
// DFS遍历树,生成路径
void gen_path(const string &s, const vector<vector<bool> > &prev,
int cur, vector<string> &path, vector<string> &result) {
if (cur == 0) {
string tmp;
for (auto iter = path.crbegin(); iter != path.crend(); ++iter)
tmp += *iter + " ";
tmp.erase(tmp.end() - 1);
result.push_back(tmp);
}
for (size_t i = 0; i < s.size(); ++i) {
if (prev[cur][i]) {
path.push_back(s.substr(i, cur - i));
gen_path(s, prev, i, path, result);
path.pop_back();
}
}
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Word Break, 见 \S \ref{sec:word-break}
\myenddot
================================================
FILE: C++/chapGraph.tex
================================================
\chapter{图}
无向图的节点定义如下:
\begin{Code}
// 无向图的节点
struct UndirectedGraphNode {
int label;
vector<UndirectedGraphNode *> neighbors;
UndirectedGraphNode(int x) : label(x) {};
};
\end{Code}
\section{Clone Graph} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:clone-graph}
\subsubsection{描述}
Clone an undirected graph. Each node in the graph contains a \code{label} and a list of its \code{neighbours}.
OJ's undirected graph serialization:
Nodes are labeled uniquely.
We use \code{\#} as a separator for each node, and \code{,} as a separator for node label and each neighbour of the node.
As an example, consider the serialized graph \code{\{0,1,2\#1,2\#2,2\}}.
The graph has a total of three nodes, and therefore contains three parts as separated by \code{\#}.
\begin{enumerate}
\item First node is labeled as 0. Connect node 0 to both nodes 1 and 2.
\item Second node is labeled as 1. Connect node 1 to node 2.
\item Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle.
\end{enumerate}
Visually, the graph looks like the following:
\begin{Code}
1
/ \
/ \
0 --- 2
/ \
\_/
\end{Code}
\subsubsection{分析}
广度优先遍历或深度优先遍历都可以。
\subsubsection{DFS}
\begin{Code}
// LeetCode, Clone Graph
// DFS,时间复杂度O(n),空间复杂度O(n)
class Solution {
public:
UndirectedGraphNode *cloneGraph(const UndirectedGraphNode *node) {
if(node == nullptr) return nullptr;
// key is original node,value is copied node
unordered_map<const UndirectedGraphNode *,
UndirectedGraphNode *> copied;
clone(node, copied);
return copied[node];
}
private:
// DFS
static UndirectedGraphNode* clone(const UndirectedGraphNode *node,
unordered_map<const UndirectedGraphNode *,
UndirectedGraphNode *> &copied) {
// a copy already exists
if (copied.find(node) != copied.end()) return copied[node];
UndirectedGraphNode *new_node = new UndirectedGraphNode(node->label);
copied[node] = new_node;
for (auto nbr : node->neighbors)
new_node->neighbors.push_back(clone(nbr, copied));
return new_node;
}
};
\end{Code}
\subsubsection{BFS}
\begin{Code}
// LeetCode, Clone Graph
// BFS,时间复杂度O(n),空间复杂度O(n)
class Solution {
public:
UndirectedGraphNode *cloneGraph(const UndirectedGraphNode *node) {
if (node == nullptr) return nullptr;
// key is original node,value is copied node
unordered_map<const UndirectedGraphNode *,
UndirectedGraphNode *> copied;
// each node in queue is already copied itself
// but neighbors are not copied yet
queue<const UndirectedGraphNode *> q;
q.push(node);
copied[node] = new UndirectedGraphNode(node->label);
while (!q.empty()) {
const UndirectedGraphNode *cur = q.front();
q.pop();
for (auto nbr : cur->neighbors) {
// a copy already exists
if (copied.find(nbr) != copied.end()) {
copied[cur]->neighbors.push_back(copied[nbr]);
} else {
UndirectedGraphNode *new_node =
new UndirectedGraphNode(nbr->label);
copied[nbr] = new_node;
copied[cur]->neighbors.push_back(new_node);
q.push(nbr);
}
}
}
return copied[node];
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item 无
\myenddot
================================================
FILE: C++/chapGreedy.tex
================================================
\chapter{贪心法}
\section{Jump Game} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:jump-game}
\subsubsection{描述}
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.
For example:
\code{A = [2,3,1,1,4]}, return true.
\code{A = [3,2,1,0,4]}, return false.
\subsubsection{分析}
由于每层最多可以跳\fn{A[i]}步,也可以跳0或1步,因此如果能到达最高层,则说明每一层都可以到达。有了这个条件,说明可以用贪心法。
思路一:正向,从0出发,一层一层网上跳,看最后能不能超过最高层,能超过,说明能到达,否则不能到达。
思路二:逆向,从最高层下楼梯,一层一层下降,看最后能不能下降到第0层。
思路三:如果不敢用贪心,可以用动规,设状态为\fn{f[i]},表示从第0层出发,走到\fn{A[i]}时剩余的最大步数,则状态转移方程为:
$$
f[i] = max(f[i-1], A[i-1])-1, i > 0
$$
\subsubsection{代码1}
\begin{Code}
// LeetCode, Jump Game
// 思路1,时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
bool canJump(const vector<int>& nums) {
int reach = 1; // 最右能跳到哪里
for (int i = 0; i < reach && reach < nums.size(); ++i)
reach = max(reach, i + 1 + nums[i]);
return reach >= nums.size();
}
};
\end{Code}
\subsubsection{代码2}
\begin{Code}
// LeetCode, Jump Game
// 思路2,时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
bool canJump (const vector<int>& nums) {
if (nums.empty()) return true;
// 逆向下楼梯,最左能下降到第几层
int left_most = nums.size() - 1;
for (int i = nums.size() - 2; i >= 0; --i)
if (i + nums[i] >= left_most)
left_most = i;
return left_most == 0;
}
};
\end{Code}
\subsubsection{代码3}
\begin{Code}
// LeetCode, Jump Game
// 思路三,动规,时间复杂度O(n),空间复杂度O(n)
class Solution {
public:
bool canJump(const vector<int>& nums) {
vector<int> f(nums.size(), 0);
f[0] = 0;
for (int i = 1; i < nums.size(); i++) {
f[i] = max(f[i - 1], nums[i - 1]) - 1;
if (f[i] < 0) return false;;
}
return f[nums.size() - 1] >= 0;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Jump Game II ,见 \S \ref{sec:jump-game-ii}
\myenddot
\section{Jump Game II} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:jump-game-ii}
\subsubsection{描述}
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
For example:
Given array \code{A = [2,3,1,1,4]}
The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)
\subsubsection{分析}
贪心法。
\subsubsection{代码1}
\begin{Code}
// LeetCode, Jump Game II
// 时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
int jump(const vector<int>& nums) {
int step = 0; // 最小步数
int left = 0;
int right = 0; // [left, right]是当前能覆盖的区间
if (nums.size() == 1) return 0;
while (left <= right) { // 尝试从每一层跳最远
++step;
const int old_right = right;
for (int i = left; i <= old_right; ++i) {
int new_right = i + nums[i];
if (new_right >= nums.size() - 1) return step;
if (new_right > right) right = new_right;
}
left = old_right + 1;
}
return 0;
}
};
\end{Code}
\subsubsection{代码2}
\begin{Code}
// LeetCode, Jump Game II
// 时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
int jump(const vector<int>& nums) {
int result = 0;
// the maximum distance that has been reached
int last = 0;
// the maximum distance that can be reached by using "ret+1" steps
int cur = 0;
for (int i = 0; i < nums.size(); ++i) {
if (i > last) {
last = cur;
++result;
}
cur = max(cur, i + nums[i]);
}
return result;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Jump Game ,见 \S \ref{sec:jump-game}
\myenddot
\section{Best Time to Buy and Sell Stock} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:best-time-to-buy-and-sell-stock}
\subsubsection{描述}
Say you have an array for which the i-th element is the price of a given stock on day i.
If 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.
\subsubsection{分析}
贪心法,分别找到价格最低和最高的一天,低进高出,注意最低的一天要在最高的一天之前。
把原始价格序列变成差分序列,本题也可以做是最大$m$子段和,$m=1$。
\subsubsection{代码}
\begin{Code}
// LeetCode, Best Time to Buy and Sell Stock
// 时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
int maxProfit(vector<int> &prices) {
if (prices.size() < 2) return 0;
int profit = 0; // 差价,也就是利润
int cur_min = prices[0]; // 当前最小
for (int i = 1; i < prices.size(); i++) {
profit = max(profit, prices[i] - cur_min);
cur_min = min(cur_min, prices[i]);
}
return profit;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Best Time to Buy and Sell Stock II,见 \S \ref{sec:best-time-to-buy-and-sell-stock-ii}
\item Best Time to Buy and Sell Stock III,见 \S \ref{sec:best-time-to-buy-and-sell-stock-iii}
\myenddot
\section{Best Time to Buy and Sell Stock II} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:best-time-to-buy-and-sell-stock-ii}
\subsubsection{描述}
Say you have an array for which the i-th element is the price of a given stock on day i.
Design 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).
\subsubsection{分析}
贪心法,低进高出,把所有正的价格差价相加起来。
把原始价格序列变成差分序列,本题也可以做是最大$m$子段和,$m=$数组长度。
\subsubsection{代码}
\begin{Code}
// LeetCode, Best Time to Buy and Sell Stock II
// 时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
int maxProfit(vector<int> &prices) {
int sum = 0;
for (int i = 1; i < prices.size(); i++) {
int diff = prices[i] - prices[i - 1];
if (diff > 0) sum += diff;
}
return sum;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Best Time to Buy and Sell Stock,见 \S \ref{sec:best-time-to-buy-and-sell-stock}
\item Best Time to Buy and Sell Stock III,见 \S \ref{sec:best-time-to-buy-and-sell-stock-iii}
\myenddot
\section{Longest Substring Without Repeating Characters} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:longest-substring-without-repeating-characters}
\subsubsection{描述}
Given 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.
\subsubsection{分析}
假设子串里含有重复字符,则父串一定含有重复字符,单个子问题就可以决定父问题,因此可以用贪心法。跟动规不同,动规里,单个子问题只能影响父问题,不足以决定父问题。
从左往右扫描,当遇到重复字母时,以上一个重复字母的\fn{index+1},作为新的搜索起始位置,直到最后一个字母,复杂度是$O(n)$。如图~\ref{fig:longest-substring-without-repeating-characters}所示。
\begin{center}
\includegraphics[width=300pt]{longest-substring-without-repeating-characters.png}\\
\figcaption{不含重复字符的最长子串}\label{fig:longest-substring-without-repeating-characters}
\end{center}
\subsubsection{代码}
\begin{Code}
// LeetCode, Longest Substring Without Repeating Characters
// 时间复杂度O(n),空间复杂度O(1)
// 考虑非字母的情况
class Solution {
public:
int lengthOfLongestSubstring(string s) {
const int ASCII_MAX = 255;
int last[ASCII_MAX]; // 记录字符上次出现过的位置
int start = 0; // 记录当前子串的起始位置
fill(last, last + ASCII_MAX, -1); // 0也是有效位置,因此初始化为-1
int max_len = 0;
for (int i = 0; i < s.size(); i++) {
if (last[s[i]] >= start) {
max_len = max(i - start, max_len);
start = last[s[i]] + 1;
}
last[s[i]] = i;
}
return max((int)s.size() - start, max_len); // 别忘了最后一次,例如"abcd"
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item 无
\myenddot
\section{Container With Most Water}
\label{sec:container-with-most-water}
\subsubsection{描述}
Given $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.
Note: You may not slant the container.
\subsubsection{分析}
每个容器的面积,取决于最短的木板。
\subsubsection{代码}
\begin{Code}
// LeetCode, Container With Most Water
// 时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
int maxArea(vector<int> &height) {
int start = 0;
int end = height.size() - 1;
int result = INT_MIN;
while (start < end) {
int area = min(height[end], height[start]) * (end - start);
result = max(result, area);
if (height[start] <= height[end]) {
start++;
} else {
end--;
}
}
return result;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Trapping Rain Water, 见 \S \ref{sec:trapping-rain-water}
\item Largest Rectangle in Histogram, 见 \S \ref{sec:largest-rectangle-in-histogram}
\myenddot
================================================
FILE: C++/chapImplement.tex
================================================
\chapter{细节实现题}
这类题目不考特定的算法,纯粹考察写代码的熟练度。
\section{Reverse Integer} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:reverse-integer}
\subsubsection{描述}
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
\textbf{Have you thought about this?}
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).
\subsubsection{分析}
短小精悍的题,代码也可以写的很短小。
\subsubsection{代码}
\begin{Code}
//LeetCode, Reverse Integer
// 时间复杂度O(logn),空间复杂度O(1)
// 考虑 1.负数的情况 2. 溢出的情况(正溢出&&负溢出,比如 x = -2147483648(即-2^31) )
class Solution {
public:
int reverse (int x) {
long long r = 0;
long long t = x;
t = t > 0 ? t : -t;
for (; t; t /= 10)
r = r * 10 + t % 10;
bool sign = x > 0 ? false: true;
if (r > 2147483647 || (sign && r > 2147483648)) {
return 0;
} else {
if (sign) {
return -r;
} else {
return r;
}
}
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Palindrome Number, 见 \S \ref{sec:palindrome-number}
\myenddot
\section{Palindrome Number} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:palindrome-number}
\subsubsection{描述}
Determine whether an integer is a palindrome. Do this without extra space.
\textbf{Some hints:}
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You 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?
There is a more generic way of solving this problem.
\subsubsection{分析}
首先想到,可以利用上一题,将整数反转,然后与原来的整数比较,是否相等,相等则为 Palindrome 的。可是 reverse()会溢出。
正确的解法是,不断地取第一位和最后一位(10进制下)进行比较,相等则取第二位和倒数第二位,直到完成比较或者中途找到了不一致的位。
\subsubsection{代码}
\begin{Code}
//LeetCode, Palindrome Number
// 时间复杂度O(1),空间复杂度O(1)
class Solution {
public:
bool isPalindrome(int x) {
if (x < 0) return false;
int d = 1; // divisor
while (x / d >= 10) d *= 10;
while (x > 0) {
int q = x / d; // quotient
int r = x % 10; // remainder
if (q != r) return false;
x = x % d / 10;
d /= 100;
}
return true;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Reverse Integer, 见 \S \ref{sec:reverse-integer}
\item Valid Palindrome, 见 \S \ref{sec:valid-palindrome}
\myenddot
\section{Insert Interval} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:insert-interval}
\subsubsection{描述}
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.
Example 1:
Given intervals \code{[1,3],[6,9]}, insert and merge \code{[2,5]} in as \code{[1,5],[6,9]}.
Example 2:
Given \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]}.
This is because the new interval \code{[4,9]} overlaps with \code{[3,5],[6,7],[8,10]}.
\subsubsection{分析}
无
\subsubsection{代码}
\begin{Code}
struct Interval {
int start;
int end;
Interval() : start(0), end(0) { }
Interval(int s, int e) : start(s), end(e) { }
};
//LeetCode, Insert Interval
// 时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) {
vector<Interval>::iterator it = intervals.begin();
while (it != intervals.end()) {
if (newInterval.end < it->start) {
intervals.insert(it, newInterval);
return intervals;
} else if (newInterval.start > it->end) {
it++;
continue;
} else {
newInterval.start = min(newInterval.start, it->start);
newInterval.end = max(newInterval.end, it->end);
it = intervals.erase(it);
}
}
intervals.insert(intervals.end(), newInterval);
return intervals;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Merge Intervals,见 \S \ref{sec:merge-intervals}
\myenddot
\section{Merge Intervals} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:merge-intervals}
\subsubsection{描述}
Given a collection of intervals, merge all overlapping intervals.
For example,
Given \code{[1,3],[2,6],[8,10],[15,18]},
return \code{[1,6],[8,10],[15,18]}
\subsubsection{分析}
复用一下Insert Intervals的解法即可,创建一个新的interval集合,然后每次从旧的里面取一个interval出来,然后插入到新的集合中。
\subsubsection{代码}
\begin{Code}
struct Interval {
int start;
int end;
Interval() : start(0), end(0) { }
Interval(int s, int e) : start(s), end(e) { }
};
//LeetCode, Merge Interval
//复用一下Insert Intervals的解法即可
// 时间复杂度O(n1+n2+...),空间复杂度O(1)
class Solution {
public:
vector<Interval> merge(vector<Interval> &intervals) {
vector<Interval> result;
for (int i = 0; i < intervals.size(); i++) {
insert(result, intervals[i]);
}
return result;
}
private:
vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) {
vector<Interval>::iterator it = intervals.begin();
while (it != intervals.end()) {
if (newInterval.end < it->start) {
intervals.insert(it, newInterval);
return intervals;
} else if (newInterval.start > it->end) {
it++;
continue;
} else {
newInterval.start = min(newInterval.start, it->start);
newInterval.end = max(newInterval.end, it->end);
it = intervals.erase(it);
}
}
intervals.insert(intervals.end(), newInterval);
return intervals;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Insert Interval,见 \S \ref{sec:insert-interval}
\myenddot
\section{Minimum Window Substring} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:minimum-window-substring}
\subsubsection{描述}
Given 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)$.
For example, \code{S = "ADOBECODEBANC", T = "ABC"}
Minimum window is \code{"BANC"}.
Note:
\begindot
\item If there is no such window in $S$ that covers all characters in $T$, return the emtpy string \code{""}.
\item If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in $S$.
\myenddot
\subsubsection{分析}
双指针,动态维护一个区间。尾指针不断往后扫,当扫到有一个窗口包含了所有$T$的字符后,然后再收缩头指针,直到不能再收缩为止。最后记录所有可能的情况中窗口最小的
\subsubsection{代码}
\begin{Code}
// LeetCode, Minimum Window Substring
// 时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
string minWindow(string S, string T) {
if (S.empty()) return "";
if (S.size() < T.size()) return "";
const int ASCII_MAX = 256;
int appeared_count[ASCII_MAX];
int expected_count[ASCII_MAX];
fill(appeared_count, appeared_count + ASCII_MAX, 0);
fill(expected_count, expected_count + ASCII_MAX, 0);
for (size_t i = 0; i < T.size(); i++) expected_count[T[i]]++;
int minWidth = INT_MAX, min_start = 0; // 窗口大小,起点
int wnd_start = 0;
int appeared = 0; // 完整包含了一个T
//尾指针不断往后扫
for (size_t wnd_end = 0; wnd_end < S.size(); wnd_end++) {
if (expected_count[S[wnd_end]] > 0) { // this char is a part of T
appeared_count[S[wnd_end]]++;
if (appeared_count[S[wnd_end]] <= expected_count[S[wnd_end]])
appeared++;
}
if (appeared == T.size()) { // 完整包含了一个T
// 收缩头指针
while (appeared_count[S[wnd_start]] > expected_count[S[wnd_start]]
|| expected_count[S[wnd_start]] == 0) {
appeared_count[S[wnd_start]]--;
wnd_start++;
}
if (minWidth > (wnd_end - wnd_start + 1)) {
minWidth = wnd_end - wnd_start + 1;
min_start = wnd_start;
}
}
}
if (minWidth == INT_MAX) return "";
else return S.substr(min_start, minWidth);
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item 无
\myenddot
\section{Multiply Strings} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:multiply-strings}
\subsubsection{描述}
Given two numbers represented as strings, return multiplication of the numbers as a string.
Note: The numbers can be arbitrarily large and are non-negative.
\subsubsection{分析}
高精度乘法。
常见的做法是将字符转化为一个int,一一对应,形成一个int数组。但是这样很浪费空间,一个int32的最大值是$2^{31}-1=2147483647$,可以与9个字符对应,由于有乘法,减半,则至少可以与4个字符一一对应。一个int64可以与9个字符对应。
\subsubsection{代码1}
\begin{Code}
// LeetCode, Multiply Strings
// @author 连城 (http://weibo.com/lianchengzju)
// 一个字符对应一个int
// 时间复杂度O(n*m),空间复杂度O(n+m)
typedef vector<int> bigint;
bigint make_bigint(string const& repr) {
bigint n;
transform(repr.rbegin(), repr.rend(), back_inserter(n),
[](char c) { return c - '0'; });
return n;
}
string to_string(bigint const& n) {
string str;
transform(find_if(n.rbegin(), prev(n.rend()),
[](char c) { return c > '\0'; }), n.rend(), back_inserter(str),
[](char c) { return c + '0'; });
return str;
}
bigint operator*(bigint const& x, bigint const& y) {
bigint z(x.size() + y.size());
for (size_t i = 0; i < x.size(); ++i)
for (size_t j = 0; j < y.size(); ++j) {
z[i + j] += x[i] * y[j];
z[i + j + 1] += z[i + j] / 10;
z[i + j] %= 10;
}
return z;
}
class Solution {
public:
string multiply(string num1, string num2) {
return to_string(make_bigint(num1) * make_bigint(num2));
}
};
\end{Code}
\subsubsection{代码2}
\begin{Code}
// LeetCode, Multiply Strings
// 9个字符对应一个int64_t
// 时间复杂度O(n*m/81),空间复杂度O((n+m)/9)
/** 大整数类. */
class BigInt {
public:
/**
* @brief 构造函数,将字符串转化为大整数.
* @param[in] s 输入的字符串
* @return 无
*/
BigInt(string s) {
vector<int64_t> result;
result.reserve(s.size() / RADIX_LEN + 1);
for (int i = s.size(); i > 0; i -= RADIX_LEN) { // [i-RADIX_LEN, i)
int temp = 0;
const int low = max(i - RADIX_LEN, 0);
for (int j = low; j < i; j++) {
temp = temp * 10 + s[j] - '0';
}
result.push_back(temp);
}
elems = result;
}
/**
* @brief 将整数转化为字符串.
* @return 字符串
*/
string toString() {
stringstream result;
bool started = false; // 用于跳过前导0
for (auto i = elems.rbegin(); i != elems.rend(); i++) {
if (started) { // 如果多余的0已经都跳过,则输出
result << setw(RADIX_LEN) << setfill('0') << *i;
} else {
result << *i;
started = true; // 碰到第一个非0的值,就说明多余的0已经都跳过
}
}
if (!started) return "0"; // 当x全为0时
else return result.str();
}
/**
* @brief 大整数乘法.
* @param[in] x x
* @param[in] y y
* @return 大整数
*/
static BigInt multiply(const BigInt &x, const BigInt &y) {
vector<int64_t> z(x.elems.size() + y.elems.size(), 0);
for (size_t i = 0; i < y.elems.size(); i++) {
for (size_t j = 0; j < x.elems.size(); j++) { // 用y[i]去乘以x的各位
// 两数第i, j位相乘,累加到结果的第i+j位
z[i + j] += y.elems[i] * x.elems[j];
if (z[i + j] >= BIGINT_RADIX) { // 看是否要进位
z[i + j + 1] += z[i + j] / BIGINT_RADIX; // 进位
z[i + j] %= BIGINT_RADIX;
}
}
}
while (z.back() == 0) z.pop_back(); // 没有进位,去掉最高位的0
return BigInt(z);
}
private:
typedef long long int64_t;
/** 一个数组元素对应9个十进制位,即数组是亿进制的
* 因为 1000000000 * 1000000000 没有超过 2^63-1
*/
const static int BIGINT_RADIX = 1000000000;
const static int RADIX_LEN = 9;
/** 万进制整数. */
vector<int64_t> elems;
BigInt(const vector<int64_t> num) : elems(num) {}
};
class Solution {
public:
string multiply(string num1, string num2) {
BigInt x(num1);
BigInt y(num2);
return BigInt::multiply(x, y).toString();
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item 无
\myenddot
\section{Substring with Concatenation of All Words} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:substring-with-concatenation-of-all-words}
\subsubsection{描述}
You 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.
For example, given:
\begin{Code}
S: "barfoothefoobarman"
L: ["foo", "bar"]
\end{Code}
You should return the indices: \code{[0,9]}.(order does not matter).
\subsubsection{分析}
无
\subsubsection{代码}
\begin{Code}
// LeetCode, Substring with Concatenation of All Words
// 时间复杂度O(n*m),空间复杂度O(m)
class Solution {
public:
vector<int> findSubstring(string s, vector<string>& dict) {
size_t wordLength = dict.front().length();
size_t catLength = wordLength * dict.size();
vector<int> result;
if (s.length() < catLength) return result;
unordered_map<string, int> wordCount;
for (auto const& word : dict) ++wordCount[word];
for (auto i = begin(s); i <= prev(end(s), catLength); ++i) {
unordered_map<string, int> unused(wordCount);
for (auto j = i; j != next(i, catLength); j += wordLength) {
auto pos = unused.find(string(j, next(j, wordLength)));
if (pos == unused.end() || pos->second == 0) break;
if (--pos->second == 0) unused.erase(pos);
}
if (unused.size() == 0) result.push_back(distance(begin(s), i));
}
return result;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item 无
\myenddot
\section{Pascal's Triangle} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:pascal-s-triangle}
\subsubsection{描述}
Given $numRows$, generate the first $numRows$ of Pascal's triangle.
For example, given $numRows = 5$,
Return
\begin{Code}
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
\end{Code}
\subsubsection{分析}
本题可以用队列,计算下一行时,给上一行左右各加一个0,然后下一行的每个元素,就等于左上角和右上角之和。
另一种思路,下一行第一个元素和最后一个元素赋值为1,中间的每个元素,等于上一行的左上角和右上角元素之和。
\subsubsection{从左到右}
\begin{Code}
// LeetCode, Pascal's Triangle
// 时间复杂度O(n^2),空间复杂度O(n)
class Solution {
public:
vector<vector<int> > generate(int numRows) {
vector<vector<int> > result;
if(numRows == 0) return result;
result.push_back(vector<int>(1,1)); //first row
for(int i = 2; i <= numRows; ++i) {
vector<int> current(i,1); // 本行
const vector<int> &prev = result[i-2]; // 上一行
for(int j = 1; j < i - 1; ++j) {
current[j] = prev[j-1] + prev[j]; // 左上角和右上角之和
}
result.push_back(current);
}
return result;
}
};
\end{Code}
\subsubsection{从右到左}
\begin{Code}
// LeetCode, Pascal's Triangle
// 时间复杂度O(n^2),空间复杂度O(n)
class Solution {
public:
vector<vector<int> > generate(int numRows) {
vector<vector<int> > result;
vector<int> array;
for (int i = 1; i <= numRows; i++) {
for (int j = i - 2; j > 0; j--) {
array[j] = array[j - 1] + array[j];
}
array.push_back(1);
result.push_back(array);
}
return result;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Pascal's Triangle II,见 \S \ref{sec:pascals-triangle-ii}
\myenddot
\section{Pascal's Triangle II} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:pascal-s-triangle-ii}
\subsubsection{描述}
Given an index $k$, return the $k^{th}$ row of the Pascal's triangle.
For example, given $k = 3$,
Return \code{[1,3,3,1]}.
Note: Could you optimize your algorithm to use only $O(k)$ extra space?
\subsubsection{分析}
滚动数组。
\subsubsection{代码}
\begin{Code}
// LeetCode, Pascal's Triangle II
// 滚动数组,时间复杂度O(n^2),空间复杂度O(n)
class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> array;
for (int i = 0; i <= rowIndex; i++) {
for (int j = i - 1; j > 0; j--){
array[j] = array[j - 1] + array[j];
}
array.push_back(1);
}
return array;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Pascal's Triangle,见 \S \ref{sec:pascals-triangle}
\myenddot
\section{Spiral Matrix} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:spiral-matrix}
\subsubsection{描述}
Given a matrix of $m \times n$ elements ($m$ rows, $n$ columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
\begin{Code}
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
\end{Code}
You should return \fn{[1,2,3,6,9,8,7,4,5]}.
\subsubsection{分析}
模拟。
\subsubsection{代码}
\begin{Code}
// LeetCode, Spiral Matrix
// @author 龚陆安 (http://weibo.com/luangong)
// 时间复杂度O(n^2),空间复杂度O(1)
class Solution {
public:
vector<int> spiralOrder(vector<vector<int> >& matrix) {
vector<int> result;
if (matrix.empty()) return result;
int beginX = 0, endX = matrix[0].size() - 1;
int beginY = 0, endY = matrix.size() - 1;
while (true) {
// From left to right
for (int j = beginX; j <= endX; ++j) result.push_back(matrix[beginY][j]);
if (++beginY > endY) break;
// From top to bottom
for (int i = beginY; i <= endY; ++i) result.push_back(matrix[i][endX]);
if (beginX > --endX) break;
// From right to left
for (int j = endX; j >= beginX; --j) result.push_back(matrix[endY][j]);
if (beginY > --endY) break;
// From bottom to top
for (int i = endY; i >= beginY; --i) result.push_back(matrix[i][beginX]);
if (++beginX > endX) break;
}
return result;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Spiral Matrix II ,见 \S \ref{sec:spiral-matrix-ii}
\myenddot
\section{Spiral Matrix II} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:spiral-matrix-ii}
\subsubsection{描述}
Given an integer $n$, generate a square matrix filled with elements from 1 to $n^2$ in spiral order.
For example,
Given $n = 3$,
You should return the following matrix:
\begin{Code}
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
\end{Code}
\subsubsection{分析}
这题比上一题要简单。
\subsubsection{代码1}
\begin{Code}
// LeetCode, Spiral Matrix II
// 时间复杂度O(n^2),空间复杂度O(n^2)
class Solution {
public:
vector<vector<int> > generateMatrix(int n) {
vector<vector<int> > matrix(n, vector<int>(n));
int begin = 0, end = n - 1;
int num = 1;
while (begin < end) {
for (int j = begin; j < end; ++j) matrix[begin][j] = num++;
for (int i = begin; i < end; ++i) matrix[i][end] = num++;
for (int j = end; j > begin; --j) matrix[end][j] = num++;
for (int i = end; i > begin; --i) matrix[i][begin] = num++;
++begin;
--end;
}
if (begin == end) matrix[begin][begin] = num;
return matrix;
}
};
\end{Code}
\subsubsection{代码2}
\begin{Code}
// LeetCode, Spiral Matrix II
// @author 龚陆安 (http://weibo.com/luangong)
// 时间复杂度O(n^2),空间复杂度O(n^2)
class Solution {
public:
vector<vector<int> > generateMatrix(int n) {
vector< vector<int> > matrix(n, vector<int>(n));
if (n == 0) return matrix;
int beginX = 0, endX = n - 1;
int beginY = 0, endY = n - 1;
int num = 1;
while (true) {
for (int j = beginX; j <= endX; ++j) matrix[beginY][j] = num++;
if (++beginY > endY) break;
for (int i = beginY; i <= endY; ++i) matrix[i][endX] = num++;
if (beginX > --endX) break;
for (int j = endX; j >= beginX; --j) matrix[endY][j] = num++;
if (beginY > --endY) break;
for (int i = endY; i >= beginY; --i) matrix[i][beginX] = num++;
if (++beginX > endX) break;
}
return matrix;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Spiral Matrix, 见 \S \ref{sec:spiral-matrix}
\myenddot
\section{ZigZag Conversion} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:zigzag-conversion}
\subsubsection{描述}
The 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)
\begin{Code}
P A H N
A P L S I I G
Y I R
\end{Code}
And then read line by line: \code{"PAHNAPLSIIGYIR"}
Write the code that will take a string and make this conversion given a number of rows:
\begin{Code}
string convert(string text, int nRows);
\end{Code}
\code{convert("PAYPALISHIRING", 3)} should return \code{"PAHNAPLSIIGYIR"}.
\subsubsection{分析}
要找到数学规律。真正面试中,不大可能出这种问题。
n=4:
\begin{Code}
P I N
A L S I G
Y A H R
P I
\end{Code}
n=5:
\begin{Code}
P H
A S I
Y I R
P L I G
A N
\end{Code}
所以,对于每一层垂直元素的坐标 $(i,j)= (j+1 )*n +i$;对于每两层垂直元素之间的插入元素(斜对角元素),$(i,j)= (j+1)*n -i$
\subsubsection{代码}
\begin{Code}
// LeetCode, ZigZag Conversion
// 时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
string convert(string s, int nRows) {
if (nRows <= 1 || s.size() <= 1) return s;
string result;
for (int i = 0; i < nRows; i++) {
for (int j = 0, index = i; index < s.size();
j++, index = (2 * nRows - 2) * j + i) {
result.append(1, s[index]); // 垂直元素
if (i == 0 || i == nRows - 1) continue; // 斜对角元素
if (index + (nRows - i - 1) * 2 < s.size())
result.append(1, s[index + (nRows - i - 1) * 2]);
}
}
return result;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item 无
\myenddot
\section{Divide Two Integers} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:divide-two-integers}
\subsubsection{描述}
Divide two integers without using multiplication, division and mod operator.
\subsubsection{分析}
不能用乘、除和取模,那剩下的,还有加、减和位运算。
最简单的方法,是不断减去被除数。在这个基础上,可以做一点优化,每次把被除数翻倍,从而加速。
\subsubsection{代码1}
\begin{Code}
// LeetCode, Divide Two Integers
// 时间复杂度O(logn),空间复杂度O(1)
class Solution {
public:
int divide(int dividend, int divisor) {
// 当 dividend = INT_MIN时,-dividend会溢出,所以用 long long
long long a = dividend >= 0 ? dividend : -(long long)dividend;
long long b = divisor >= 0 ? divisor : -(long long)divisor;
// 当 dividend = INT_MIN时,divisor = -1时,结果会溢出,所以用 long long
long long result = 0;
while (a >= b) {
long long c = b;
for (int i = 0; a >= c; ++i, c <<= 1) {
a -= c;
result += 1 << i;
}
}
return ((dividend^divisor) >> 31) ? (-result) : (result);
}
};
\end{Code}
\subsubsection{代码2}
\begin{Code}
// LeetCode, Divide Two Integers
// 时间复杂度O(logn),空间复杂度O(1)
class Solution {
public:
int divide(int dividend, int divisor) {
int result = 0; // 当 dividend = INT_MIN时,divisor = -1时,结果会溢出
const bool sign = (dividend > 0 && divisor < 0) ||
(dividend < 0 && divisor > 0); // 异号
// 当 dividend = INT_MIN时,-dividend会溢出,所以用 unsigned int
unsigned int a = dividend >= 0 ? dividend : -dividend;
unsigned int b = divisor >= 0 ? divisor : -divisor;
while (a >= b) {
int multi = 1;
unsigned int bb = b;
while (a >= bb) {
a -= bb;
result += multi;
if (bb < INT_MAX >> 1) { // 防止溢出
bb += bb;
multi += multi;
}
}
}
if (sign) return -result;
else return result;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item 无
\myenddot
\section{Text Justification} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:text-justification}
\subsubsection{描述}
Given 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.
You 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.
Extra 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.
For the last line of text, it should be left justified and no extra space is inserted between words.
For example, \\
words: \code{["This", "is", "an", "example", "of", "text", "justification."]} \\
L: 16.
Return the formatted lines as:
\begin{Code}
[
"This is an",
"example of text",
"justification. "
]
\end{Code}
Note: Each word is guaranteed not to exceed $L$ in length.
Corner Cases:
\begindot
\item A line other than the last line might contain only one word. What should you do in this case?
\item In this case, that line should be left
\myenddot
\subsubsection{分析}
无
\subsubsection{代码}
\begin{Code}
// LeetCode, Text Justification
// 时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
vector<string> fullJustify(vector<string> &words, int L) {
vector<string> result;
const int n = words.size();
int begin = 0, len = 0; // 当前行的起点,当前长度
for (int i = 0; i < n; ++i) {
if (len + words[i].size() + (i - begin) > L) {
result.push_back(connect(words, begin, i - 1, len, L, false));
begin = i;
len = 0;
}
len += words[i].size();
}
// 最后一行不足L
result.push_back(connect(words, begin, n - 1, len, L, true));
return result;
}
/**
* @brief 将 words[begin, end] 连成一行
* @param[in] words 单词列表
* @param[in] begin 开始
* @param[in] end 结束
* @param[in] len words[begin, end]所有单词加起来的长度
* @param[in] L 题目规定的一行长度
* @param[in] is_last 是否是最后一行
* @return 对齐后的当前行
*/
string connect(vector<string> &words, int begin, int end,
int len, int L, bool is_last) {
string s;
int n = end - begin + 1;
for (int i = 0; i < n; ++i) {
s += words[begin + i];
addSpaces(s, i, n - 1, L - len, is_last);
}
if (s.size() < L) s.append(L - s.size(), ' ');
return s;
}
/**
* @brief 添加空格.
* @param[inout]s 一行
* @param[in] i 当前空隙的序号
* @param[in] n 空隙总数
* @param[in] L 总共需要添加的空额数
* @param[in] is_last 是否是最后一行
* @return 无
*/
void addSpaces(string &s, int i, int n, int L, bool is_last) {
if (n < 1 || i > n - 1) return;
int spaces = is_last ? 1 : (L / n + (i < (L % n) ? 1 : 0));
s.append(spaces, ' ');
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item 无
\myenddot
\section{Max Points on a Line} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:max-points-on-a-line}
\subsubsection{描述}
Given $n$ points on a 2D plane, find the maximum number of points that lie on the same straight line.
\subsubsection{分析}
暴力枚举法。两点决定一条直线,$n$个点两两组合,可以得到$\dfrac{1}{2}n(n+1)$条直线,对每一条直线,判断$n$个点是否在该直线上,从而可以得到这条直线上的点的个数,选择最大的那条直线返回。复杂度$O(n^3)$。
上面的暴力枚举法以“边”为中心,再看另一种暴力枚举法,以每个“点”为中心,然后遍历剩余点,找到所有的斜率,如果斜率相同,那么一定共线对每个点,用一个哈希表,key为斜率,value为该直线上的点数,计算出哈希表后,取最大值,并更新全局最大值,最后就是结果。时间复杂度$O(n^2)$,空间复杂度$O(n)$。
\subsubsection{以边为中心}
\begin{Code}
// LeetCode, Max Points on a Line
// 暴力枚举法,以边为中心,时间复杂度O(n^3),空间复杂度O(1)
class Solution {
public:
int maxPoints(vector<Point> &points) {
if (points.size() < 3) return points.size();
int result = 0;
for (int i = 0; i < points.size() - 1; i++) {
for (int j = i + 1; j < points.size(); j++) {
int sign = 0;
int a, b, c;
if (points[i].x == points[j].x) sign = 1;
else {
a = points[j].x - points[i].x;
b = points[j].y - points[i].y;
c = a * points[i].y - b * points[i].x;
}
int count = 0;
for (int k = 0; k < points.size(); k++) {
if ((0 == sign && a * points[k].y == c + b * points[k].x) ||
(1 == sign&&points[k].x == points[j].x))
count++;
}
if (count > result) result = count;
}
}
return result;
}
};
\end{Code}
\subsubsection{以点为中心}
\begin{Code}
// LeetCode, Max Points on a Line
// 暴力枚举,以点为中心,时间复杂度O(n^2),空间复杂度O(n)
class Solution {
public:
int maxPoints(vector<Point> &points) {
if (points.size() < 3) return points.size();
int result = 0;
unordered_map<double, int> slope_count;
for (int i = 0; i < points.size()-1; i++) {
slope_count.clear();
int samePointNum = 0; // 与i重合的点
int point_max = 1; // 和i共线的最大点数
for (int j = i + 1; j < points.size(); j++) {
double slope; // 斜率
if (points[i].x == points[j].x) {
slope = std::numeric_limits<double>::infinity();
if (points[i].y == points[j].y) {
++ samePointNum;
continue;
}
} else {
slope = 1.0 * (points[i].y - points[j].y) /
(points[i].x - points[j].x);
}
int count = 0;
if (slope_count.find(slope) != slope_count.end())
count = ++slope_count[slope];
else {
count = 2;
slope_count[slope] = 2;
}
if (point_max < count) point_max = count;
}
result = max(result, point_max + samePointNum);
}
return result;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item 无
\myenddot
================================================
FILE: C++/chapLinearList.tex
================================================
\chapter{线性表}
这类题目考察线性表的操作,例如,数组,单链表,双向链表等。
\section{数组} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{Remove Duplicates from Sorted Array}
\label{sec:remove-duplicates-from-sorted-array}
\subsubsection{描述}
Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
For example, Given input array \code{A = [1,1,2]},
Your function should return length = 2, and A is now \code{[1,2]}.
\subsubsection{分析}
无
\subsubsection{代码1}
\begin{Code}
// LeetCode, Remove Duplicates from Sorted Array
// 时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if (nums.empty()) return 0;
int index = 0;
for (int i = 1; i < nums.size(); i++) {
if (nums[index] != nums[i])
nums[++index] = nums[i];
}
return index + 1;
}
};
\end{Code}
\subsubsection{代码2}
\begin{Code}
// LeetCode, Remove Duplicates from Sorted Array
// 使用STL,时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
return distance(nums.begin(), unique(nums.begin(), nums.end()));
}
};
\end{Code}
\subsubsection{代码3}
\begin{Code}
// LeetCode, Remove Duplicates from Sorted Array
// 使用STL,时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
return distance(nums.begin(), removeDuplicates(nums.begin(), nums.end(), nums.begin()));
}
template<typename InIt, typename OutIt>
OutIt removeDuplicates(InIt first, InIt last, OutIt output) {
while (first != last) {
*output++ = *first;
first = upper_bound(first, last, *first);
}
return output;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Remove Duplicates from Sorted Array II,见 \S \ref{sec:remove-duplicates-from-sorted-array-ii}
\myenddot
\subsection{Remove Duplicates from Sorted Array II}
\label{sec:remove-duplicates-from-sorted-array-ii}
\subsubsection{描述}
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array \code{A = [1,1,1,2,2,3]},
Your function should return length = 5, and A is now \code{[1,1,2,2,3]}
\subsubsection{分析}
加一个变量记录一下元素出现的次数即可。这题因为是已经排序的数组,所以一个变量即可解决。如果是没有排序的数组,则需要引入一个hashmap来记录出现次数。
\subsubsection{代码1}
\begin{Code}
// LeetCode, Remove Duplicates from Sorted Array II
// 时间复杂度O(n),空间复杂度O(1)
// @author hex108 (https://github.com/hex108)
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if (nums.size() <= 2) return nums.size();
int index = 2;
for (int i = 2; i < nums.size(); i++){
if (nums[i] != nums[index - 2])
nums[index++] = nums[i];
}
return index;
}
};
\end{Code}
\subsubsection{代码2}
下面是一个更简洁的版本。上面的代码略长,不过扩展性好一些,例如将\fn{occur < 2}改为\fn{occur < 3},就变成了允许重复最多3次。
\begin{Code}
// LeetCode, Remove Duplicates from Sorted Array II
// @author 虞航仲 (http://weibo.com/u/1666779725)
// 时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
const int n = nums.size();
int index = 0;
for (int i = 0; i < n; ++i) {
if (i > 0 && i < n - 1 && nums[i] == nums[i - 1] && nums[i] == nums[i + 1])
continue;
nums[index++] = nums[i];
}
return index;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Remove Duplicates from Sorted Array,见 \S \ref{sec:remove-duplicates-from-sorted-array}
\myenddot
\subsection{Search in Rotated Sorted Array}
\label{sec:search-in-rotated-sorted-array}
\subsubsection{描述}
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e., \code{0 1 2 4 5 6 7} might become \code{4 5 6 7 0 1 2}).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
\subsubsection{分析}
二分查找,难度主要在于左右边界的确定。
\subsubsection{代码}
\begin{Code}
// LeetCode, Search in Rotated Sorted Array
// 时间复杂度O(log n),空间复杂度O(1)
class Solution {
public:
int search(const vector<int>& nums, int target) {
int first = 0, last = nums.size();
while (first != last) {
const int mid = first + (last - first) / 2;
if (nums[mid] == target)
return mid;
if (nums[first] <= nums[mid]) {
if (nums[first] <= target && target < nums[mid])
last = mid;
else
first = mid + 1;
} else {
if (nums[mid] < target && target <= nums[last-1])
first = mid + 1;
else
last = mid;
}
}
return -1;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Search in Rotated Sorted Array II,见 \S \ref{sec:search-in-rotated-sorted-array-ii}
\myenddot
\subsection{Search in Rotated Sorted Array II}
\label{sec:search-in-rotated-sorted-array-ii}
\subsubsection{描述}
Follow up for "Search in Rotated Sorted Array": What if \emph{duplicates} are allowed?
Would this affect the run-time complexity? How and why?
Write a function to determine if a given target is in the array.
\subsubsection{分析}
允许重复元素,则上一题中如果\fn{A[m]>=A[l]},那么\fn{[l,m]}为递增序列的假设就不能成立了,比如\code{[1,3,1,1,1]}。
如果\fn{A[m]>=A[l]}不能确定递增,那就把它拆分成两个条件:
\begindot
\item 若\fn{A[m]>A[l]},则区间\fn{[l,m]}一定递增
\item 若\fn{A[m]==A[l]} 确定不了,那就\fn{l++},往下看一步即可。
\myenddot
\subsubsection{代码}
\begin{Code}
// LeetCode, Search in Rotated Sorted Array II
// 时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
bool search(const vector<int>& nums, int target) {
int first = 0, last = nums.size();
while (first != last) {
const int mid = first + (last - first) / 2;
if (nums[mid] == target)
return true;
if (nums[first] < nums[mid]) {
if (nums[first] <= target && target < nums[mid])
last = mid;
else
first = mid + 1;
} else if (nums[first] > nums[mid]) {
if (nums[mid] < target && target <= nums[last-1])
first = mid + 1;
else
last = mid;
} else
//skip duplicate one
first++;
}
return false;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Search in Rotated Sorted Array,见 \S \ref{sec:search-in-rotated-sorted-array}
\myenddot
\subsection{Median of Two Sorted Arrays}
\label{sec:median-of-two-sorted-arrays}
\subsubsection{描述}
There 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))$.
\subsubsection{分析}
这是一道非常经典的题。这题更通用的形式是,给定两个已经排序好的数组,找到两者所有元素中第$k$大的元素。
$O(m+n)$的解法比较直观,直接merge两个数组,然后求第$k$大的元素。
不过我们仅仅需要第$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)$的。
有没有更好的方案呢?我们可以考虑从$k$入手。如果我们每次都能够删除一个一定在第$k$大元素之前的元素,那么我们需要进行$k$次。但是如果每次我们都删除一半呢?由于A和B都是有序的,我们应该充分利用这里面的信息,类似于二分查找,也是充分利用了“有序”。
假设A和B的元素个数都大于$k/2$,我们将A的第$k/2$个元素(即\fn{A[k/2-1]})和B的第$k/2$个元素(即\fn{B[k/2-1]})进行比较,有以下三种情况(为了简化这里先假设$k$为偶数,所得到的结论对于$k$是奇数也是成立的):
\begindot
\item \fn{A[k/2-1] == B[k/2-1]}
\item \fn{A[k/2-1] > B[k/2-1]}
\item \fn{A[k/2-1] < B[k/2-1]}
\myenddot
如果\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$大元素。留给读者证明。
因此,我们可以放心的删除A数组的这$k/2$个元素。同理,当\fn{A[k/2-1] > B[k/2-1]}时,可以删除B数组的$k/2$个元素。
当\fn{A[k/2-1] == B[k/2-1]}时,说明找到了第$k$大的元素,直接返回\fn{A[k/2-1]}或\fn{B[k/2-1]}即可。
因此,我们可以写一个递归函数。那么函数什么时候应该终止呢?
\begindot
\item 当A或B是空时,直接返回\fn{B[k-1]}或\fn{A[k-1]};
\item 当\fn{k=1}是,返回\fn{min(A[0], B[0])};
\item 当\fn{A[k/2-1] == B[k/2-1]}时,返回\fn{A[k/2-1]}或\fn{B[k/2-1]}
\myenddot
\subsubsection{代码}
\begin{Code}
// LeetCode, Median of Two Sorted Arrays
// 时间复杂度O(log(m+n)),空间复杂度O(log(m+n))
class Solution {
public:
double findMedianSortedArrays(const vector<int>& A, const vector<int>& B) {
const int m = A.size();
const int n = B.size();
int total = m + n;
if (total & 0x1)
return find_kth(A.begin(), m, B.begin(), n, total / 2 + 1);
else
return (find_kth(A.begin(), m, B.begin(), n, total / 2)
+ find_kth(A.begin(), m, B.begin(), n, total / 2 + 1)) / 2.0;
}
private:
static int find_kth(std::vector<int>::const_iterator A, int m,
std::vector<int>::const_iterator B, int n, int k) {
//always assume that m is equal or smaller than n
if (m > n) return find_kth(B, n, A, m, k);
if (m == 0) return *(B + k - 1);
if (k == 1) return min(*A, *B);
//divide k into two parts
int ia = min(k / 2, m), ib = k - ia;
if (*(A + ia - 1) < *(B + ib - 1))
return find_kth(A + ia, m - ia, B, n, k - ia);
else if (*(A + ia - 1) > *(B + ib - 1))
return find_kth(A, m, B + ib, n - ib, k - ib);
else
return A[ia - 1];
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item 无
\myenddot
\subsection{Longest Consecutive Sequence} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:longest-consecutive-sequence}
\subsubsection{描述}
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given \code{[100, 4, 200, 1, 3, 2]},
The longest consecutive elements sequence is \code{[1, 2, 3, 4]}. Return its length: 4.
Your algorithm should run in $O(n)$ complexity.
\subsubsection{分析}
如果允许$O(n \log n)$的复杂度,那么可以先排序,可是本题要求$O(n)$。
由于序列里的元素是无序的,又要求$O(n)$,首先要想到用哈希表。
用一个哈希表 \fn{unordered_map<int, bool> used}记录每个元素是否使用,对每个元素,以该元素为中心,往左右扩张,直到不连续为止,记录下最长的长度。
\subsubsection{代码}
\begin{Code}
// Leet Code, Longest Consecutive Sequence
// 时间复杂度O(n),空间复杂度O(n)
class Solution {
public:
int longestConsecutive(const vector<int> &nums) {
unordered_map<int, bool> used;
for (auto i : nums) used[i] = false;
int longest = 0;
for (auto i : nums) {
if (used[i]) continue;
int length = 1;
used[i] = true;
for (int j = i + 1; used.find(j) != used.end(); ++j) {
used[j] = true;
++length;
}
for (int j = i - 1; used.find(j) != used.end(); --j) {
used[j] = true;
++length;
}
longest = max(longest, length);
}
return longest;
}
};
\end{Code}
\subsubsection{分析2}
第一直觉是个聚类的操作,应该有union,find的操作.连续序列可以用两端和长度来表示.
本来用两端就可以表示,但考虑到查询的需求,将两端分别暴露出来.用\fn{unordered_map<int, int> map}来
存储.原始思路来自于\url{http://discuss.leetcode.com/questions/1070/longest-consecutive-sequence}
\subsubsection{代码}
\begin{Code}
// Leet Code, Longest Consecutive Sequence
// 时间复杂度O(n),空间复杂度O(n)
// Author: @advancedxy
class Solution {
public:
int longestConsecutive(vector<int> &nums) {
unordered_map<int, int> map;
int size = nums.size();
int l = 1;
for (int i = 0; i < size; i++) {
if (map.find(nums[i]) != map.end()) continue;
map[nums[i]] = 1;
if (map.find(nums[i] - 1) != map.end()) {
l = max(l, mergeCluster(map, nums[i] - 1, nums[i]));
}
if (map.find(nums[i] + 1) != map.end()) {
l = max(l, mergeCluster(map, nums[i], nums[i] + 1));
}
}
return size == 0 ? 0 : l;
}
private:
int mergeCluster(unordered_map<int, int> &map, int left, int right) {
int upper = right + map[right] - 1;
int lower = left - map[left] + 1;
int length = upper - lower + 1;
map[upper] = length;
map[lower] = length;
return length;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item 无
\myenddot
\subsection{Two Sum} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:Two-sum}
\subsubsection{描述}
Given an array of integers, find two numbers such that they add up to a specific target number.
The 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.
You may assume that each input would have exactly one solution.
Input: \code{numbers=\{2, 7, 11, 15\}, target=9}
Output: \code{index1=1, index2=2}
\subsubsection{分析}
方法1:暴力,复杂度$O(n^2)$,会超时
方法2:hash。用一个哈希表,存储每个数对应的下标,复杂度$O(n)$.
方法3:先排序,然后左右夹逼,排序$O(n\log n)$,左右夹逼$O(n)$,最终$O(n\log n)$。但是注意,这题需要返回的是下标,而不是数字本身,因此这个方法行不通。
\subsubsection{代码}
\begin{Code}
//LeetCode, Two Sum
// 方法2:hash。用一个哈希表,存储每个数对应的下标
// 时间复杂度O(n),空间复杂度O(n)
class Solution {
public:
vector<int> twoSum(vector<int> &nums, int target) {
unordered_map<int, int> mapping;
vector<int> result;
for (int i = 0; i < nums.size(); i++) {
mapping[nums[i]] = i;
}
for (int i = 0; i < nums.size(); i++) {
const int gap = target - nums[i];
if (mapping.find(gap) != mapping.end() && mapping[gap] > i) {
result.push_back(i + 1);
result.push_back(mapping[gap] + 1);
break;
}
}
return result;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item 3Sum, 见 \S \ref{sec:3sum}
\item 3Sum Closest, 见 \S \ref{sec:3sum-closest}
\item 4Sum, 见 \S \ref{sec:4sum}
\myenddot
\subsection{3Sum} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:3sum}
\subsubsection{描述}
Given 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.
Note:
\begindot
\item Elements in a triplet $(a,b,c)$ must be in non-descending order. (ie, $a \leq b \leq c$)
\item The solution set must not contain duplicate triplets.
\myenddot
For example, given array \code{S = \{-1 0 1 2 -1 -4\}}.
A solution set is:
\begin{Code}
(-1, 0, 1)
(-1, -1, 2)
\end{Code}
\subsubsection{分析}
先排序,然后左右夹逼,复杂度 $O(n^2)$。
这个方法可以推广到$k$-sum,先排序,然后做$k-2$次循环,在最内层循环左右夹逼,时间复杂度是 $O(\max\{n \log n, n^{k-1}\})$。
\subsubsection{代码}
\begin{Code}
// LeetCode, 3Sum
// 先排序,然后左右夹逼,注意跳过重复的数,时间复杂度O(n^2),空间复杂度O(1)
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> result;
if (nums.size() < 3) return result;
sort(nums.begin(), nums.end());
const int target = 0;
auto last = nums.end();
for (auto i = nums.begin(); i < last-2; ++i) {
auto j = i+1;
if (i > nums.begin() && *i == *(i-1)) continue;
auto k = last-1;
while (j < k) {
if (*i + *j + *k < target) {
++j;
while(*j == *(j - 1) && j < k) ++j;
} else if (*i + *j + *k > target) {
--k;
while(*k == *(k + 1) && j < k) --k;
} else {
result.push_back({ *i, *j, *k });
++j;
--k;
while(*j == *(j - 1) && *k == *(k + 1) && j < k) ++j;
}
}
}
return result;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Two sum, 见 \S \ref{sec:Two-sum}
\item 3Sum Closest, 见 \S \ref{sec:3sum-closest}
\item 4Sum, 见 \S \ref{sec:4sum}
\myenddot
\subsection{3Sum Closest} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:3sum-closest}
\subsubsection{描述}
Given 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.
For example, given array \code{S = \{-1 2 1 -4\}}, and \code{target = 1}.
The sum that is closest to the target is 2. (\code{-1 + 2 + 1 = 2}).
\subsubsection{分析}
先排序,然后左右夹逼,复杂度 $O(n^2)$。
\subsubsection{代码}
\begin{Code}
// LeetCode, 3Sum Closest
// 先排序,然后左右夹逼,时间复杂度O(n^2),空间复杂度O(1)
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int result = 0;
int min_gap = INT_MAX;
sort(nums.begin(), nums.end());
for (auto a = nums.begin(); a != prev(nums.end(), 2); ++a) {
auto b = next(a);
auto c = prev(nums.end());
while (b < c) {
const int sum = *a + *b + *c;
const int gap = abs(sum - target);
if (gap < min_gap) {
result = sum;
min_gap = gap;
}
if (sum < target) ++b;
else --c;
}
}
return result;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Two sum, 见 \S \ref{sec:Two-sum}
\item 3Sum, 见 \S \ref{sec:3sum}
\item 4Sum, 见 \S \ref{sec:4sum}
\myenddot
\subsection{4Sum} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:4sum}
\subsubsection{描述}
Given 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.
Note:
\begindot
\item Elements in a quadruplet $(a,b,c,d)$ must be in non-descending order. (ie, $a \leq b \leq c \leq d$)
\item The solution set must not contain duplicate quadruplets.
\myenddot
For example, given array \code{S = \{1 0 -1 0 -2 2\}}, and \code{target = 0}.
A solution set is:
\begin{Code}
(-1, 0, 0, 1)
(-2, -1, 1, 2)
(-2, 0, 0, 2)
\end{Code}
\subsubsection{分析}
先排序,然后左右夹逼,复杂度 $O(n^3)$,会超时。
可以用一个hashmap先缓存两个数的和,最终复杂度$O(n^3)$。这个策略也适用于 3Sum 。
\subsubsection{左右夹逼}
\begin{Code}
// LeetCode, 4Sum
// 先排序,然后左右夹逼,时间复杂度O(n^3),空间复杂度O(1)
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> result;
if (nums.size() < 4) return result;
sort(nums.begin(), nums.end());
auto last = nums.end();
for (auto a = nums.begin(); a < prev(last, 3); ++a) {
for (auto b = next(a); b < prev(last, 2); ++b) {
auto c = next(b);
auto d = prev(last);
while (c < d) {
if (*a + *b + *c + *d < target) {
++c;
} else if (*a + *b + *c + *d > target) {
--d;
} else {
result.push_back({ *a, *b, *c, *d });
++c;
--d;
}
}
}
}
sort(result.begin(), result.end());
result.erase(unique(result.begin(), result.end()), result.end());
return result;
}
};
\end{Code}
\subsubsection{map做缓存}
\begin{Code}
// LeetCode, 4Sum
// 用一个hashmap先缓存两个数的和
// 时间复杂度,平均O(n^2),最坏O(n^4),空间复杂度O(n^2)
class Solution {
public:
vector<vector<int> > fourSum(vector<int> &nums, int target) {
vector<vector<int>> result;
if (nums.size() < 4) return result;
sort(nums.begin(), nums.end());
unordered_map<int, vector<pair<int, int> > > cache;
for (size_t a = 0; a < nums.size(); ++a) {
for (size_t b = a + 1; b < nums.size(); ++b) {
cache[nums[a] + nums[b]].push_back(pair<int, int>(a, b));
}
}
for (int c = 0; c < nums.size(); ++c) {
for (size_t d = c + 1; d < nums.size(); ++d) {
const int key = target - nums[c] - nums[d];
if (cache.find(key) == cache.end()) continue;
const auto& vec = cache[key];
for (size_t k = 0; k < vec.size(); ++k) {
if (c <= vec[k].second)
continue; // 有重叠
result.push_back( { nums[vec[k].first],
nums[vec[k].second], nums[c], nums[d] });
}
}
}
sort(result.begin(), result.end());
result.erase(unique(result.begin(), result.end()), result.end());
return result;
}
};
\end{Code}
\subsubsection{multimap}
\begin{Code}
// LeetCode, 4Sum
// 用一个 hashmap 先缓存两个数的和
// 时间复杂度O(n^2),空间复杂度O(n^2)
// @author 龚陆安(http://weibo.com/luangong)
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> result;
if (nums.size() < 4) return result;
sort(nums.begin(), nums.end());
unordered_multimap<int, pair<int, int>> cache;
for (int i = 0; i + 1 < nums.size(); ++i)
for (int j = i + 1; j < nums.size(); ++j)
cache.insert(make_pair(nums[i] + nums[j], make_pair(i, j)));
for (auto i = cache.begin(); i != cache.end(); ++i) {
int x = target - i->first;
auto range = cache.equal_range(x);
for (auto j = range.first; j != range.second; ++j) {
auto a = i->second.first;
auto b = i->second.second;
auto c = j->second.first;
auto d = j->second.second;
if (a != c && a != d && b != c && b != d) {
vector<int> vec = { nums[a], nums[b], nums[c], nums[d] };
sort(vec.begin(), vec.end());
result.push_back(vec);
}
}
}
sort(result.begin(), result.end());
result.erase(unique(result.begin(), result.end()), result.end());
return result;
}
};
\end{Code}
\subsubsection{方法4}
\begin{Code}
// LeetCode, 4Sum
// 先排序,然后左右夹逼,时间复杂度O(n^3logn),空间复杂度O(1),会超时
// 跟方法1相比,表面上优化了,实际上更慢了,切记!
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> result;
if (nums.size() < 4) return result;
sort(nums.begin(), nums.end());
auto last = nums.end();
for (auto a = nums.begin(); a < prev(last, 3);
a = upper_bound(a, prev(last, 3), *a)) {
for (auto b = next(a); b < prev(last, 2);
b = upper_bound(b, prev(last, 2), *b)) {
auto c = next(b);
auto d = prev(last);
while (c < d) {
if (*a + *b + *c + *d < target) {
c = upper_bound(c, d, *c);
} else if (*a + *b + *c + *d > target) {
d = prev(lower_bound(c, d, *d));
} else {
result.push_back({ *a, *b, *c, *d });
c = upper_bound(c, d, *c);
d = prev(lower_bound(c, d, *d));
}
}
}
}
return result;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Two sum, 见 \S \ref{sec:Two-sum}
\item 3Sum, 见 \S \ref{sec:3sum}
\item 3Sum Closest, 见 \S \ref{sec:3sum-closest}
\myenddot
\subsection{Remove Element} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:remove-element }
\subsubsection{描述}
Given an array and a value, remove all instances of that value in place and return the new length.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
\subsubsection{分析}
无
\subsubsection{代码1}
\begin{Code}
// LeetCode, Remove Element
// 时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
int removeElement(vector<int>& nums, int target) {
int index = 0;
for (int i = 0; i < nums.size(); ++i) {
if (nums[i] != target) {
nums[index++] = nums[i];
}
}
return index;
}
};
\end{Code}
\subsubsection{代码2}
\begin{Code}
// LeetCode, Remove Element
// 使用remove(),时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
int removeElement(vector<int>& nums, int target) {
return distance(nums.begin(), remove(nums.begin(), nums.end(), target));
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item 无
\myenddot
\subsection{Next Permutation} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:next-permutation}
\subsubsection{描述}
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-place, do not allocate extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
\begin{Code}
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1
\end{Code}
\subsubsection{分析}
算法过程如图~\ref{fig:permutation}所示(来自\myurl{http://fisherlei.blogspot.com/2012/12/leetcode-next-permutation.html})。
\begin{center}
\includegraphics[width=360pt]{next-permutation.png}\\
\figcaption{下一个排列算法流程}\label{fig:permutation}
\end{center}
\subsubsection{代码}
\begin{Code}
// LeetCode, Next Permutation
// 时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
void nextPermutation(vector<int> &nums) {
next_permutation(nums.begin(), nums.end());
}
template<typename BidiIt>
bool next_permutation(BidiIt first, BidiIt last) {
// Get a reversed range to simplify reversed traversal.
const auto rfirst = reverse_iterator<BidiIt>(last);
const auto rlast = reverse_iterator<BidiIt>(first);
// Begin from the second last element to the first element.
auto pivot = next(rfirst);
// Find `pivot`, which is the first element that is no less than its
// successor. `Prev` is used since `pivort` is a `reversed_iterator`.
while (pivot != rlast && *pivot >= *prev(pivot))
++pivot;
// No such elemenet found, current sequence is already the largest
// permutation, then rearrange to the first permutation and return false.
if (pivot == rlast) {
reverse(rfirst, rlast);
return false;
}
// Scan from right to left, find the first element that is greater than
// `pivot`.
auto change = find_if(rfirst, pivot, bind1st(less<int>(), *pivot));
swap(*change, *pivot);
reverse(rfirst, pivot);
return true;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Permutation Sequence, 见 \S \ref{sec:permutation-sequence}
\item Permutations, 见 \S \ref{sec:permutations}
\item Permutations II, 见 \S \ref{sec:permutations-ii}
\item Combinations, 见 \S \ref{sec:combinations}
\myenddot
\subsection{Permutation Sequence} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:permutation-sequence}
\subsubsection{描述}
The set \fn{[1,2,3,…,n]} contains a total of $n!$ unique permutations.
By listing and labeling all of the permutations in order,
We get the following sequence (ie, for $n = 3$):
\begin{Code}
"123"
"132"
"213"
"231"
"312"
"321"
\end{Code}
Given $n$ and $k$, return the kth permutation sequence.
Note: Given $n$ will be between 1 and 9 inclusive.
\subsubsection{分析}
简单的,可以用暴力枚举法,调用 $k-1$ 次 \fn{next_permutation()}。
暴力枚举法把前 $k$个排列都求出来了,比较浪费,而我们只需要第$k$个排列。
利用康托编码的思路,假设有$n$个不重复的元素,第$k$个排列是$a_1, a_2, a_3, ..., a_n$,那么$a_1$是哪一个位置呢?
我们把$a_1$去掉,那么剩下的排列为
$a_2, a_3, ..., a_n$, 共计$n-1$个元素,$n-1$个元素共有$(n-1)!$个排列,于是就可以知道 $a_1 = k / (n-1)!$。
同理,$a_2, a_3, ..., a_n$的值推导如下:
\begin{eqnarray}
k_2 &=& k\%(n-1)! \nonumber \\
a_2 &=& k_2/(n-2)! \nonumber \\
\quad & \cdots \nonumber \\
k_{n-1} &=& k_{n-2}\%2! \nonumber \\
a_{n-1} &=& k_{n-1}/1! \nonumber \\
a_n &=& 0 \nonumber
\end{eqnarray}
\subsubsection{使用next_permutation()}
\begin{Code}
// LeetCode, Permutation Sequence
// 使用next_permutation(),TLE
class Solution {
public:
string getPermutation(int n, int k) {
string s(n, '0');
for (int i = 0; i < n; ++i)
s[i] += i+1;
for (int i = 0; i < k-1; ++i)
next_permutation(s.begin(), s.end());
return s;
}
template<typename BidiIt>
bool next_permutation(BidiIt first, BidiIt last) {
// 代码见上一题 Next Permutation
}
};
\end{Code}
\subsubsection{康托编码}
\begin{Code}
// LeetCode, Permutation Sequence
// 康托编码,时间复杂度O(n),空间复杂度O(1)
class Solution {
public:
string getPermutation(int n, int k) {
string s(n, '0');
string result;
for (int i = 0; i < n; ++i)
s[i] += i + 1;
return kth_permutation(s, k);
}
private:
int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; ++i)
result *= i;
return result;
}
// seq 已排好序,是第一个排列
template<typename Sequence>
Sequence kth_permutation(const Sequence &seq, int k) {
const int n = seq.size();
Sequence S(seq);
Sequence result;
int base = factorial(n - 1);
--k; // 康托编码从0开始
for (int i = n - 1; i > 0; k %= base, base /= i, --i) {
auto a = next(S.begin(), k / base);
result.push_back(*a);
S.erase(a);
}
result.push_back(S[0]); // 最后一个
return result;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Next Permutation, 见 \S \ref{sec:next-permutation}
\item Permutations, 见 \S \ref{sec:permutations}
\item Permutations II, 见 \S \ref{sec:permutations-ii}
\item Combinations, 见 \S \ref{sec:combinations}
\myenddot
\subsection{Valid Sudoku} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:valid-sudoku}
\subsubsection{描述}
Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules \myurl{http://sudoku.com.au/TheRules.aspx} .
The Sudoku board could be partially filled, where empty cells are filled with the character \fn{'.'}.
\begin{center}
\includegraphics[width=150pt]{sudoku.png}\\
\figcaption{A partially filled sudoku which is valid}\label{fig:sudoku}
\end{center}
\subsubsection{分析}
细节实现题。
\subsubsection{代码}
\begin{Code}
// LeetCode, Valid Sudoku
// 时间复杂度O(n^2),空间复杂度O(1)
class Solution {
public:
bool isValidSudoku(const vector<vector<char>>& board) {
bool used[9];
for (int i = 0; i < 9; ++i) {
fill(used, used + 9, false);
for (int j = 0; j < 9; ++j) // 检查行
if (!check(board[i][j], used))
return false;
fill(used, used + 9, false);
for (int j = 0; j < 9; ++j) // 检查列
if (!check(board[j][i], used))
return false;
}
for (int r = 0; r < 3; ++r) // 检查 9 个子格子
for (int c = 0; c < 3; ++c) {
fill(used, used + 9, false);
for (int i = r * 3; i < r * 3 + 3; ++i)
for (int j = c * 3; j < c * 3 + 3; ++j)
if (!check(board[i][j], used))
return false;
}
return true;
}
bool check(char ch, bool used[9]) {
if (ch == '.') return true;
if (used[ch - '1']) return false;
return used[ch - '1'] = true;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Sudoku Solver, 见 \S \ref{sec:sudoku-solver}
\myenddot
\subsection{Trapping Rain Water} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:trapping-rain-water}
\subsubsection{描述}
Given $n$ non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able
gitextract_i3l5z3yw/ ├── .devcontainer/ │ └── devcontainer.json ├── .gitignore ├── .vscode/ │ └── tasks.json ├── C++/ │ ├── README.md │ ├── abstract.tex │ ├── chapBFS.tex │ ├── chapBruteforce.tex │ ├── chapDFS.tex │ ├── chapDivideAndConquer.tex │ ├── chapDynamicProgramming.tex │ ├── chapGraph.tex │ ├── chapGreedy.tex │ ├── chapImplement.tex │ ├── chapLinearList.tex │ ├── chapSearching.tex │ ├── chapSorting.tex │ ├── chapStackAndQueue.tex │ ├── chapString.tex │ ├── chapTree.tex │ ├── chapTrick.tex │ ├── format.cls │ ├── leetcode-cpp.tex │ ├── tex-text-tt.tec │ ├── title.tex │ └── verbatim.cls ├── Java/ │ └── README.md ├── LICENSE └── README.md
Condensed preview — 28 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (374K chars).
[
{
"path": ".devcontainer/devcontainer.json",
"chars": 112,
"preview": "{\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",
"chars": 43,
"preview": "*.log\n*.toc\n*.aux\n*.idx\n*.out\n*.synctex.gz\n"
},
{
"path": ".vscode/tasks.json",
"chars": 760,
"preview": "{\n \"version\": \"2.0.0\",\n \"tasks\": [\n {\n \"label\": \"lettcode-C++\",\n \"type\": \"shell\",\n "
},
{
"path": "C++/README.md",
"chars": 149,
"preview": "# C++版\n\n## 编译\n\n```bash\ndocker run -it --rm -v $(pwd):/project -w /project soulmachine/texlive xelatex -interaction=nonst"
},
{
"path": "C++/abstract.tex",
"chars": 906,
"preview": "\\subsubsection{内容简介}\n本书的目标读者是准备去北美找工作的码农,也适用于在国内找工作的码农,以及刚接触ACM算法竞赛的新手。\n\n本书包含了 LeetCode Online Judge(\\myurl{http://leetc"
},
{
"path": "C++/chapBFS.tex",
"chars": 34634,
"preview": "\\chapter{广度优先搜索}\n当题目看不出任何规律,既不能用分治,贪心,也不能用动规时,这时候万能方法——搜索,\n就派上用场了。搜索分为广搜和深搜,广搜里面又有普通广搜,双向广搜,A*搜索等。\n深搜里面又有普通深搜,回溯法等。\n\n广搜和"
},
{
"path": "C++/chapBruteforce.tex",
"chars": 19245,
"preview": "\\chapter{暴力枚举法}\n\n\n\\section{Subsets} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:subsets}\n\n\n\\subsubsection{描述}\nGiven a set "
},
{
"path": "C++/chapDFS.tex",
"chars": 33226,
"preview": "\\chapter{深度优先搜索}\n\n\n\\section{Palindrome Partitioning} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:palindrome-partitioning}\n"
},
{
"path": "C++/chapDivideAndConquer.tex",
"chars": 1653,
"preview": "\\chapter{分治法}\n\n\n\\section{Pow(x,n)} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:pow}\n\n\n\\subsubsection{描述}\nImplement pow(x, "
},
{
"path": "C++/chapDynamicProgramming.tex",
"chars": 32331,
"preview": "\\chapter{动态规划}\n\n\n\\section{Triangle} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:triangle}\n\n\n\\subsubsection{描述}\nGiven a tri"
},
{
"path": "C++/chapGraph.tex",
"chars": 3581,
"preview": "\\chapter{图}\n\n无向图的节点定义如下:\n\\begin{Code}\n// 无向图的节点\nstruct UndirectedGraphNode {\n int label;\n vector<UndirectedGraphNo"
},
{
"path": "C++/chapGreedy.tex",
"chars": 9320,
"preview": "\\chapter{贪心法}\n\n\n\\section{Jump Game} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:jump-game}\n\n\n\\subsubsection{描述}\nGiven an a"
},
{
"path": "C++/chapImplement.tex",
"chars": 30727,
"preview": "\\chapter{细节实现题}\n这类题目不考特定的算法,纯粹考察写代码的熟练度。\n\n\n\\section{Reverse Integer} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:reverse-i"
},
{
"path": "C++/chapLinearList.tex",
"chars": 73083,
"preview": "\\chapter{线性表}\n这类题目考察线性表的操作,例如,数组,单链表,双向链表等。\n\n\n\\section{数组} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\\subsection{Remove Duplicate"
},
{
"path": "C++/chapSearching.tex",
"chars": 5185,
"preview": "\\chapter{查找}\n\n\n\\section{Search for a Range} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:search-for-a-range}\n\n\n\\subsubsecti"
},
{
"path": "C++/chapSorting.tex",
"chars": 10410,
"preview": "\\chapter{排序}\n\n\\section{Merge Two Sorted Arrays} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:merge-two-sorted-arrays}\n\n\n\\su"
},
{
"path": "C++/chapStackAndQueue.tex",
"chars": 8989,
"preview": "\\chapter{栈和队列}\n\n\n\\section{栈} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\\subsection{Valid Parentheses} %%%%%%%%%%%%%%%%%%%%%%%%%%%"
},
{
"path": "C++/chapString.tex",
"chars": 28914,
"preview": "\\chapter{字符串}\n\n\n\\section{Valid Palindrome} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\\label{sec:valid-palindrome}\n\n\n\\subsubsection{"
},
{
"path": "C++/chapTree.tex",
"chars": 49318,
"preview": "\\chapter{树}\n\nLeetCode 上二叉树的节点定义如下:\n\\begin{Code}\n// 树的节点\nstruct TreeNode {\n int val;\n TreeNode *left;\n TreeNode "
},
{
"path": "C++/chapTrick.tex",
"chars": 805,
"preview": "\\chapter{编程技巧}\n\n在判断两个浮点数a和b是否相等时,不要用\\fn{a==b},应该判断二者之差的绝对值\\fn{fabs(a-b)}是否小于某个阈值,例如\\fn{1e-9}。\n\n判断一个整数是否是为奇数,用\\fn{x \\% 2 "
},
{
"path": "C++/format.cls",
"chars": 3252,
"preview": "\\usepackage[centering,paperwidth=180mm,paperheight=230mm,%\nbody={390pt,530pt},marginparsep=10pt,marginpar=50pt]{geometry"
},
{
"path": "C++/leetcode-cpp.tex",
"chars": 1161,
"preview": "\\documentclass[10pt,adobefonts,fancyhdr,hyperref,UTF8]{ctexbook}\n\n\\usepackage{multirow}\n% for \\soul 删除线\n\\usepackage{ulem"
},
{
"path": "C++/title.tex",
"chars": 459,
"preview": "\\thispagestyle{plain}\n\\begin{center}\n {\\LARGE\\textbf{\\BookTitle}}\n\n \\vspace{1em}\n {\\large 灵魂机器 (soulmachine@gmail.com"
},
{
"path": "C++/verbatim.cls",
"chars": 2856,
"preview": "\\def\\FV@SetLineWidth{%\n \\if@FV@ResetMargins\\else\n \\advance\\leftmargin\\@totalleftmargin\n \\fi\n \\advance\\leftmargin\\F"
},
{
"path": "Java/README.md",
"chars": 205,
"preview": "#Java版\n-----------------\n\n## 编译\n\n docker pull soulmachine/texlive\n docker run -it --rm -v $(pwd):/data -w /data so"
},
{
"path": "LICENSE",
"chars": 1501,
"preview": "Copyright (c) 2013, soulmachine and The Contributors\nAll rights reserved.\n\nRedistribution and use in source and binary f"
},
{
"path": "README.md",
"chars": 1069,
"preview": "# LeetCode题解\n\n## 在线阅读\n\n<https://algorithm-essentials.soulmachine.me/>\n\n## PDF下载\n\n<a href=\"https://github.com/soulmachine"
}
]
// ... and 1 more files (download for full content)
About this extraction
This page contains the full source code of the soulmachine/leetcode GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 28 files (345.6 KB), approximately 113.6k tokens. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.