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);
            }
        }
    }
  • 相关阅读:
    learn go memoization
    learn go return fuction
    Java5 并发学习
    Java中的protected访问修饰符
    LinkedBlockingQueue
    BlockingQueue的使用
    Java并发编程:Callable、Future和FutureTask
    Java线程池的工作原理与实现
    SQL Server中Delete语句表名不能用别名
    请问JDBC中IN语句怎么构建
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10078100.html
Copyright © 2011-2022 走看看