美文网首页
40. 组合总和 II

40. 组合总和 II

作者: 梦想黑客 | 来源:发表于2020-03-03 17:04 被阅读0次

题目描述

给定一个数组 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]
]

解法

class Solution {
    List<List<Integer>> result = new ArrayList<>();
    Set<List<Integer>> set = new HashSet<>();
    
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        if(candidates == null || candidates.length == 0) return result;
        
        Arrays.sort(candidates);
        List<Integer> item = new ArrayList<>();
        
        generate(0,candidates,target,item);
        return result;
    }
    
    private void generate(int start,int[] candidates,int target,List<Integer> item){
        if(target < 0) return;
        
        if(target == 0 && !set.contains(item)){
            result.add(new ArrayList<>(item));
            set.add(item);
        }else{
            
            for(int i=start;i<candidates.length;i++){
                if(candidates[i] > target) continue;
                item.add(candidates[i]);
                generate(i+1,candidates,target - candidates[i],item);
                item.remove(item.size() - 1);
            }
            
        }
        
    }
}

相关文章

网友评论

      本文标题:40. 组合总和 II

      本文链接:https://www.haomeiwen.com/subject/tdghlhtx.html