您的位置:首页 > 其它

leetcode 40-Combination Sum II

2017-04-24 12:20 531 查看
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> list = new ArrayList<>();
List<Integer> temp = new ArrayList<>();
Arrays.sort(candidates); //和39比,多了这一步,39不限制使用次数,排不排序都不影响
backtrack(list, temp, candidates, target, 0, 0);
return list;
}

private void backtrack(List<List<Integer>> list, List<Integer> temp,
int[] candidates, int target, int index, int sum) {
if (sum > target) return;
if (sum == target) list.add(new ArrayList<Integer>(temp));
if (sum < target) {
for (int i = index; i < candidates.length; i++) {
if (i > index && candidates[i] == candidates[i - 1])
continue; //和39比多了这一步,因为不允许重复
temp.add(candidates[i]);
backtrack(list, temp, candidates, target, i + 1,
sum + candidates[i]); //这里是i+1,还是因为次数限制
temp.remove(temp.size() - 1);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode