39. 组合总和

39. 组合总和

class Solution {
    List<List<Integer>> res = new ArrayList<>();
    LinkedList<Integer> path = new LinkedList<>();
    HashSet<HashMap<Integer,Integer>> set = new HashSet();
    HashMap<Integer,Integer> map = new HashMap();
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        backtracking(0,candidates,target);
        return res;
    }
    public void backtracking(int sum,int[] candidates,int target){
        if(sum == target){
            if(!set.contains(map)){
                set.add(new HashMap(map));
                res.add(new ArrayList<>(path));
            }
            return;    
        }else{
            for(int i = 0; i < candidates.length;i++){
                if(sum + candidates[i] > target) break;
                else{
                    sum += candidates[i];
                    path.addLast(candidates[i]);
                    map.put(candidates[i],map.getOrDefault(candidates[i], 0) + 1);
                    backtracking(sum,candidates,target);
                    map.put(candidates[i],map.getOrDefault(candidates[i], 0) - 1);
                    if(map.getOrDefault(candidates[i], 0) == 0) map.remove(candidates[i]);
                    path.pollLast();
                    sum -= candidates[i];
                }
            }
        }
    }
}

这个方法效率很低啊,用Hashmap来记录每个组合,set储存,如果已经存在就不加入res中去,candidates要先排序一下,从最小的开始遍历,不然很多情况都会被略过。

class Solution {
    List<List<Integer>> res = new ArrayList<>();
    LinkedList<Integer> path = new LinkedList<>();
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        backtracking(0,candidates,target,0);
        return res;
    }
    //标记start起始点,是为了防止后续循环再从头开始遍历,可以直接从start开始遍历,避免了重复,因为candidates已经排序过了,可以囊括所有情况
    public void backtracking(int sum,int[] candidates,int target, int start){
        if(sum == target){
            res.add(new ArrayList<>(path));
            return;    
        }

        for(int i = start; i < candidates.length;i++){
            if(sum + candidates[i] > target) break;
            path.addLast(candidates[i]);
            backtracking(sum + candidates[i],candidates,target,i);
            path.pollLast();

        }
    }
}

start是为了防止中间节点往前遍历从而出现重复,而对数组进行排序是为了从最小值开始循环,避免漏了一些情况,比如数组[3,2,1,1] target = 2,如果从3开始遍历,则直接返回空。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值