File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1- 学习笔记
1+ 第三周学习笔记
2+ 本周学习了递归,学会了递归模板:
3+ 1 . recursion terminator(递归终止条件)
4+ 2 . process logic in current level (处理当前逻辑层)
5+ 3 . drill down (下探到下一层)
6+ 4 . reverse the current level status if needed (清理当前层)
7+
8+ 学习了分治思想及回溯
9+
10+
11+
Original file line number Diff line number Diff line change 1+
2+ //题目:组合
3+ //回溯法
4+
5+ class Solution {
6+ List <List <Integer >> output = new LinkedList ();
7+ int n ;
8+ int k ;
9+
10+ public void backtrack (int first , LinkedList <Integer > curr ) {
11+ // if the combination is done
12+ if (curr .size () == k )
13+ output .add (new LinkedList (curr ));
14+
15+ for (int i = first ; i < n + 1 ; ++i ) {
16+ // add i into the current combination
17+ curr .add (i );
18+ // use next integers to complete the combination
19+ backtrack (i + 1 , curr );
20+ // backtrack
21+ curr .removeLast ();
22+ }
23+ }
24+
25+ public List <List <Integer >> combine (int n , int k ) {
26+ this .n = n ;
27+ this .k = k ;
28+ backtrack (1 , new LinkedList <Integer >());
29+ return output ;
30+ }
31+ }
32+
Original file line number Diff line number Diff line change 1+
2+ //题目: 全排列
3+
4+
5+ //回溯
6+
7+ class Solution {
8+ public void backtrack (int n ,
9+ ArrayList <Integer > output ,
10+ List <List <Integer >> res ,
11+ int first ) {
12+ // 所有数都填完了
13+ if (first == n )
14+ res .add (new ArrayList <Integer >(output ));
15+ for (int i = first ; i < n ; i ++) {
16+ // 动态维护数组
17+ Collections .swap (output , first , i );
18+ // 继续递归填下一个数
19+ backtrack (n , output , res , first + 1 );
20+ // 撤销操作
21+ Collections .swap (output , first , i );
22+ }
23+ }
24+
25+ public List <List <Integer >> permute (int [] nums ) {
26+ List <List <Integer >> res = new LinkedList ();
27+
28+ ArrayList <Integer > output = new ArrayList <Integer >();
29+ for (int num : nums )
30+ output .add (num );
31+
32+ int n = nums .length ;
33+ backtrack (n , output , res , 0 );
34+ return res ;
35+ }
36+ }
You can’t perform that action at this time.
0 commit comments