组合总和Ⅱ

Leetcode题目描述

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

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

回溯算法demo + Hash

  • 可以先进行数组排序,然后按照大小依次遍历
  • 不在HashMap的内容添加到HashMap,已在HashMap的内容跳过
class Solution {
    HashMap<List<Integer>, Integer> hashMap = new HashMap<List<Integer>, Integer>();
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates); // 排序后先利用原有的数组
        List<List<Integer>> res = new ArrayList<>();
        backtrack(0 , target, candidates, new ArrayList<Integer>(), res);
        return res;
    }

    public void backtrack(int s,  int t, int[] nums, List<Integer> tmp, List<List<Integer>> res){
        if( t == 0 && !hashMap.containsKey(tmp)){
            hashMap.put(tmp, 1);
            res.add(new ArrayList<Integer>(tmp));
            return;
        }
        
        for(;  s < nums.length; s++){
            if( t - nums[s] >= 0){
                tmp.add(nums[s]);
                backtrack(s + 1, t - nums[s],  nums, tmp, res);
                tmp.remove(tmp.size() - 1);
            }
        }
    }
}
原文地址:https://www.cnblogs.com/Di-iD/p/13784984.html