Skip to content

Commit 94aa964

Browse files
author
邵联飞
committed
提交
1 parent 6e7361a commit 94aa964

3 files changed

Lines changed: 79 additions & 1 deletion

File tree

Week03/NOTE.md

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,11 @@
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+

Week03/first.java

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
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+

Week03/second.java

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
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+
}

0 commit comments

Comments
 (0)