leetcode 40. Combination Sum II-回溯算法

来源:互联网 发布:淘宝淘金币怎么获得 编辑:程序博客网 时间:2024/04/30 11:29
原题链接:40. Combination Sum II

【思路-Java】递归实现

本题是 leetcode 39. Combination Sum-回溯算法|递归|非递归 的延伸,本题中给定的数组元素有重复。对于[1,1,2],如果还是采用原先的处理,结果集中肯定会有重复的元素出现,那么怎么处理呢?方法就是只对本层循环中重复元素出现进行调用,而对下一层递归中重复元素跳过递归调用。为了使重复元素相邻,我们首先要对数组排序。接下来就可以使用一行代码对重复情况进行排除:

public class Solution {    public List<List<Integer>> combinationSum2(int[] candidates, int target) {        List<List<Integer>> res = new ArrayList<>();        Arrays.sort(candidates);        dfs(res, new ArrayList<Integer>(), target, candidates, 0);        return res;    }    private void dfs(List<List<Integer>> res, List<Integer> temp, int target, int[] candidates, int i) {        if(target == 0)            res.add(new ArrayList<>(temp));        for(int j = i; j < candidates.length && target >= candidates[j]; j++) {            if(j > i && candidates[j] == candidates[j-1]) continue;            temp.add(candidates[j]);            dfs(res, temp, target-candidates[j], candidates, j+1);            temp.remove(temp.size()-1);        }    }}
172 / 172 test cases passed. Runtime: 5 ms  Your runtime beats 77.41% of javasubmissions.

1 0
原创粉丝点击