问一道leetcode上的题目 combination sum# JobHunting - 待字闺中
y*d
1 楼
LC 39
code 如下
两处不明白
1. 为什么要先排序?
2. 为什么helper(res, target-candidates[i], tmp, candidates, i); 是i不是
i+1??
多谢指点
public List
code 如下
两处不明白
1. 为什么要先排序?
2. 为什么helper(res, target-candidates[i], tmp, candidates, i); 是i不是
i+1??
多谢指点
public List
- > combinationSum(int[] candidates, int target) {
List
- > res = new ArrayList
- >();
if (candidates == null || candidates.length == 0) {
return res;
}
Arrays.sort(candidates);
helper(res, target, new ArrayList
return res;
}
void helper(List
- > res, int target, List
] candidates, int start) {
if (target == 0) {
res.add(new ArrayList(tmp));
}
for (int i = start; i < candidates.length && target >= candidates[i]
; i++) {
tmp.add(candidates[i]);
helper(res, target-candidates[i], tmp, candidates, i);
tmp.remove(tmp.size()-1);
}
}