zoukankan      html  css  js  c++  java
  • 组合总和Ⅱ

    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);
                }
            }
        }
    }
    
  • 相关阅读:
    BZOJ1511: [POI2006]OKR-Periods of Words
    BZOJ1009: [HNOI2008]GT考试
    BZOJ1355: [Baltic2009]Radio Transmission
    BZOJ1415: [Noi2005]聪聪和可可
    BZOJ1004: [HNOI2008]Cards
    UVA11077 Find the Permutations
    LA3641 Leonardo's Notebook
    UVA10294 Arif in Dhaka
    UVA11762 Race to 1
    UVA11427 Expect the Expected
  • 原文地址:https://www.cnblogs.com/Di-iD/p/13784984.html
Copyright © 2011-2022 走看看