forked from soulmachine/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chapDFS.tex
1123 lines (882 loc) · 37.3 KB
/
chapDFS.tex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
\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;
}
// s[0, prev-1]之间已经处理,保证是回文串
// prev 表示s[prev-1]与s[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) {
// 0行和0列未使用
this->f = vector<vector<int> >(m + 1, vector<int>(n + 1, 0));
return dfs(m, n);
}
private:
vector<vector<int> > f; // 缓存
int dfs(int x, int y) {
if (x < 1 || y < 1) return 0; // 数据非法,终止条件
if (x == 1 && y == 1) return 1; // 回到起点,收敛条件
return getOrUpdate(x - 1, y) + getOrUpdate(x, y - 1);
}
int getOrUpdate(int x, int y) {
if (f[x][y] > 0) return f[x][y];
else return f[x][y] = dfs(x, y);
}
};
\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 - 1] + f[j];
}
}
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(vector<vector<int> > &obstacleGrid) {
const int m = obstacleGrid.size();
const int n = obstacleGrid[0].size();
// 0行和0列未使用
this->f = vector<vector<int> >(m + 1, vector<int>(n + 1, 0));
return dfs(obstacleGrid, m, n);
}
private:
vector<vector<int> > f; // 缓存
int dfs(const vector<vector<int> > &obstacleGrid,
int x, int y) {
if (x < 1 || y < 1) return 0; // 数据非法,终止条件
// (x,y)是障碍
if (obstacleGrid[x-1][y-1]) return 0;
if (x == 1 and y == 1) return 1; // 回到起点,收敛条件
return getOrUpdate(obstacleGrid, x - 1, y) +
getOrUpdate(obstacleGrid, x, y - 1);
}
int getOrUpdate(const vector<vector<int> > &obstacleGrid,
int x, int y) {
if (f[x][y] > 0) return f[x][y];
else return f[x][y] = dfs(obstacleGrid, x, y);
}
};
\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++)
for (int j = 0; j < n; j++)
f[j] = obstacleGrid[i][j] ? 0 : (j == 0 ? 0 : f[j - 1]) + f[j];
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{分析}
经典的深搜题。
\subsubsection{代码}
\begin{Code}
// LeetCode, N-Queens
// 深搜+剪枝
// 时间复杂度O(n!),空间复杂度O(n)
class Solution {
public:
vector<vector<string> > solveNQueens(int n) {
this->columns = vector<int>(n, 0);
this->main_diag = vector<int>(2 * n, 0);
this->anti_diag = vector<int>(2 * n, 0);
vector<vector<string> > result;
vector<int> C(n, 0); // C[i]表示第i行皇后所在的列编号
dfs(C, result, 0);
return result;
}
private:
// 这三个变量用于剪枝
vector<int> columns; // 表示已经放置的皇后占据了哪些列
vector<int> main_diag; // 占据了哪些主对角线
vector<int> 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] == 0 && main_diag[row + j] == 0 &&
anti_diag[row - j + N] == 0;
if (!ok) continue; // 剪枝:如果合法,继续递归
// 执行扩展动作
C[row] = j;
columns[j] = main_diag[row + j] = anti_diag[row - j + N] = 1;
dfs(C, result, row + 1);
// 撤销动作
// C[row] = 0;
columns[j] = main_diag[row + j] = anti_diag[row - j + N] = 0;
}
}
};
\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{代码}
\begin{Code}
// LeetCode, N-Queens II
// 深搜+剪枝
// 时间复杂度O(n!),空间复杂度O(n)
class Solution {
public:
int totalNQueens(int n) {
this->count = 0;
this->columns = vector<int>(n, 0);
this->main_diag = vector<int>(2 * n, 0);
this->anti_diag = vector<int>(2 * n, 0);
vector<int> C(n, 0); // C[i]表示第i行皇后所在的列编号
dfs(C, 0);
return this->count;
}
private:
int count; // 解的个数
// 这三个变量用于剪枝
vector<int> columns; // 表示已经放置的皇后占据了哪些列
vector<int> main_diag; // 占据了哪些主对角线
vector<int> 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] == 0 &&
main_diag[row + j] == 0 &&
anti_diag[row - j + N] == 0;
if (!ok) continue; // 剪枝:如果合法,继续递归
// 执行扩展动作
C[row] = j;
columns[j] = main_diag[row + j] =
anti_diag[row - j + N] = 1;
dfs(C, row + 1);
// 撤销动作
// C[row] = 0;
columns[j] = main_diag[row + j] =
anti_diag[row - j + N] = 0;
}
}
};
\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(string s) {
vector<string> result;
string ip; // 存放中间结果
dfs(s, 0, 0, ip, result);
return result;
}
/**
* @brief 解析字符串
* @param[in] s 字符串,输入数据
* @param[in] startIndex 从s的哪里开始
* @param[in] step 当前步骤编号,从0开始编号,取值为0,1,2,3,4表示结束了
* @param[out] intermediate 当前解析出来的中间结果
* @param[out] result 存放所有可能的IP地址
* @return 无
*/
void dfs(string s, size_t start, size_t step, string ip,
vector<string> &result) {
if (start == s.size() && step == 4) { // 找到一个合法解
ip.resize(ip.size() - 1);
result.push_back(ip);
return;
}
if (s.size() - start > (4 - step) * 3)
return; // 剪枝
if (s.size() - start < (4 - step))
return; // 剪枝
int num = 0;
for (size_t i = start; i < start + 3; i++) {
num = num * 10 + (s[i] - '0');
if (num <= 255) { // 当前结点合法,则继续往下递归
ip += s[i];
dfs(s, i + 1, step + 1, ip + '.', result);
}
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 > a_2 > ... > 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> intermediate; // 中间结果
dfs(nums, target, 0, intermediate, result);
return result;
}
private:
void dfs(vector<int>& nums, int gap, int start, vector<int>& intermediate,
vector<vector<int> > &result) {
if (gap == 0) { // 找到一个合法解
result.push_back(intermediate);
return;
}
for (size_t i = start; i < nums.size(); i++) { // 扩展状态
if (gap < nums[i]) return; // 剪枝
intermediate.push_back(nums[i]); // 执行扩展动作
dfs(nums, gap - nums[i], i, intermediate, result);
intermediate.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 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{once} 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 > 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> intermediate;
dfs(nums, target, 0, intermediate, result);
return result;
}
private:
// 使用nums[start, nums.size())之间的元素,能找到的所有可行解
static void dfs(vector<int> &nums, int gap, int start,
vector<int> &intermediate, vector<vector<int> > &result) {
if (gap == 0) { // 找到一个合法解
result.push_back(intermediate);
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];
intermediate.push_back(nums[i]);
dfs(nums, gap - nums[i], i + 1, intermediate, result);
intermediate.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;
if (n > 0) generate(n, "", 0, 0, result);
return result;
}
// l 表示 ( 出现的次数, r 表示 ) 出现的次数
void generate(int n, string s, int l, int r, vector<string> &result) {
if (l == n) {
result.push_back(s.append(n - r, ')'));
return;
}
generate(n, s + '(', l + 1, r, result);
if (l > r) generate(n, s + ")", l, r + 1, result);
}
};
\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(vector<vector<char> > &board, 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) || // 左