zoukankan      html  css  js  c++  java
  • 40. Combination Sum II

    Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

    Each number in candidates may only be used once in the combination.

    Note:

    • All numbers (including target) will be positive integers.
    • The solution set must not contain duplicate combinations.

    Example 1:

    Input: candidates = [10,1,2,7,6,1,5], target = 8,
    A solution set is:
    [
      [1, 7],
      [1, 2, 5],
      [2, 6],
      [1, 1, 6]
    ]
    

    Example 2:

    Input: candidates = [2,5,2,1,2], target = 5,
    A solution set is:
    [
      [1,2,2],
      [5]
    ]

    backtracking

    和I不同的地方是数组里可以有重复元素,要注意去重

    去重:1. 用set; 2. 判断同一个元素是否在同一递归深度出现

    s = target / min(nums[i]), T = C(s, 1) + C(s, 2) + ... + C(s, s) = 2^s  -> O(2^s)

    time: O(2^s), space: O( target / min(nums[i]) )

    class Solution {
        public List<List<Integer>> combinationSum2(int[] candidates, int target) {
            List<List<Integer>> res = new ArrayList<>();
            Arrays.sort(candidates);
            backtracking(candidates, target, 0, new ArrayList<>(), res);
            return res;
        }
        
        private void backtracking(int[] candidates, int target, int idx, List<Integer> tmp, List<List<Integer>> res) {
            if(target == 0) res.add(new ArrayList<>(tmp));
            
            for(int i = idx; i < candidates.length; i++) {
                if(candidates[i] > target) break;
                if(i > idx && candidates[i] == candidates[i-1]) continue;
                tmp.add(candidates[i]);
                backtracking(candidates, target - candidates[i], i + 1, tmp, res);
                tmp.remove(tmp.size() - 1);
            }
        }
    }
  • 相关阅读:
    MYSQL 优化指南
    设计模式——依赖倒置原则实例(PHP实现)
    PHP开发笔记
    反射应用
    HMAC-SHA1算法签名及Authorization头认证
    PHP接口和抽象类的区别
    PHP 模板方法模式使用
    RSA JS 加密解密DEMO
    RSA加密解密(PHP Demo)
    【Spark调优】提交job资源参数调优
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10078100.html
Copyright © 2011-2022 走看看