【leetcode 39】 combination sum 组合总和

“The Linux philosophy is “Laugh in the face of danger”.Oops.Wrong One. “Do it yourself”. Yes, that”s it.”
Linux的哲学就是“在危险面前放声大笑”,呵呵,不是这句,应该是“一切靠自己,自力更生”才对。

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

* 给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
* candidates 中的数字可以无限制重复被选取。
*
* dfs即可
*/
public class {
public List<List<Integer>> combinationSum (int[] candidates, int target) {
List<List<Integer>> res = new LinkedList<>();
helper(res, new LinkedList<Integer>(), target, candidates,0);
return res;
}

private void helper (List<List<Integer>> res, List<Integer> bag, int target, int[] nums,int pos) {
if (target == 0) {
res.add(bag);
return;
}
if (target < 0)
return;
else {
for (int i = pos; i < nums.length; i++) {
List<Integer> temp = new LinkedList<>(bag);
bag.add(nums[i]);
helper(res, bag, target - nums[i], nums,i);
bag = temp;
}
}

}
}