选或不选的经典题目

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
class Solution {
int[] candidates;
List<List<Integer>> ans;
List<Integer> path;

/**
* 选或不选的经典题目
*/
public List<List<Integer>> combinationSum(int[] candidates, int target) {
this.ans = new ArrayList<>();
this.candidates = candidates;
this.path = new ArrayList<>();
dfs(0, target);
return ans;
}

private void dfs(int i, int target) {
if (target == 0) {
ans.add(new ArrayList<>(path));
return ;
}
if (target < 0) return ;
if (i >= candidates.length) return ;
path.add(candidates[i]);
dfs(i, target - candidates[i]);
path.remove(path.size() - 1);
dfs(i+1, target);
}
}

Comments
Recent Posts
计算机网络
进程树
进程管理
Categories
Website Info
Article Count :
4
Total Word Count :
14.4k
Unique Visitors :
Page Views :
Last Update :