1212-2019-LEETCODE- la somme combinée de 2 (numéro de composition non répétable)

Code de la clé

//在for循环中添加遇到与前一个数相等的数时就跳过的代码,如下
for(int i = start;i < candicates.size && residue - candicates[i] >= 0;i++){
	if(i > start && candicates[i] == candicates[i - 1]){
		countinue;
	}
}
private List<List<Integer>> res = new ArrayList<>();
    private int[] candidates;
    private int len;

    private void findCombinationSum2(int residue, int start, Stack<Integer> pre) {
        if (residue == 0) {
            // Java 中可变对象是引用传递,因此需要将当前 path 里的值拷贝出来
            res.add(new ArrayList<>(pre));
            return;
        }
        // 优化添加的代码2:在循环的时候做判断,尽量避免系统栈的深度
        // residue - candidates[i] 表示下一轮的剩余,如果下一轮的剩余都小于 0 ,就没有必要进行后面的循环了
        // 这一点基于原始数组是排序数组的前提,因为如果计算后面的剩余,只会越来越小
        for (int i = start; i < len && residue - candidates[i] >= 0; i++) {
            if (i > start && candidates[i] == candidates[i - 1]){
                continue;
            }
            pre.add(candidates[i]);
            // 【关键】因为元素可以重复使用,这里递归传递下去的是 i 而不是 i + 1
            findCombinationSum2(residue - candidates[i], i + 1, pre);
            pre.pop();
        }

    }

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        int len = candidates.length;
        if (len == 0) {
            return res;
        }
        // 优化添加的代码1:先对数组排序,可以提前终止判断
        Arrays.sort(candidates);
        this.len = len;
        this.candidates = candidates;
        findCombinationSum2(target, 0, new Stack<>());
        return res;
    }
Publié 98 articles originaux · louanges gagnées 0 · Vues 2220

Je suppose que tu aimes

Origine blog.csdn.net/weixin_43221993/article/details/103570267
conseillé
Classement