• 组合总和 去重


    给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

    candidates 中的每个数字在每个组合中只能使用一次。

    说明:

    所有数字(包括目标数)都是正整数。
    解集不能包含重复的组合。 
    示例 1:

    输入: candidates = [10,1,2,7,6,1,5], target = 8,
    所求解集为:
    [
    [1, 7],
    [1, 2, 5],
    [2, 6],
    [1, 1, 6]
    ]
    示例 2:

    输入: candidates = [2,5,2,1,2], target = 5,
    所求解集为:
    [
      [1,2,2],
      [5]
    ]

    /**
     * @param {number[]} candidates
     * @param {number} target
     * @return {number[][]}
     */
    function comp(a,b){
        return a-b;
    }
    var combinationSum2 = function(candidates, target) {
          let temp  = [];
    
        candidates.sort(comp);
        var check = function(str,sum,index){
            if(sum === target){
                temp.push(str.slice());
                return ;
            }
            if(sum>target){
                return;
            }
    
            for(let i=index;i<candidates.length;i++){
                if(i>index&&candidates[i] == candidates[i-1]) continue;//
                    sum = sum +candidates[i];
                    str.push(candidates[i]);
                    check(str,sum,i+1)
                    str.pop();
                    sum = sum - candidates[i];
               
            }
    
        }
        check([],0,0);
        return temp;
    };

    实现方式:回溯,但是这个题的最主要的是,去重部分, i>index&&candidates[i] == candidates[i-1] ,假如当前路径已经组合完毕之后,就要进行回溯到上一层路径,然后再向后组合路径,这里I>index,如果向后要组合数据和前一位相同就不用再执行了,会出现重复列表,直接continue就可以了。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/combination-sum-ii
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

  • 相关阅读:
    关于各种好玩的神奇函数
    模板——AC自动机
    模板——造数据
    VIM常用操作
    springboot注解
    面试题
    Linux常用命令
    Zookeeper
    对cpu与load的理解及线上问题处理思路
    top
  • 原文地址:https://www.cnblogs.com/panjingshuang/p/11673545.html
Copyright © 2020-2023  润新知