zoukankan      html  css  js  c++  java
  • [LC] 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]
    ]

    Time: O(2^N)
    Space: O(N)
    class Solution {
        public List<List<Integer>> combinationSum2(int[] candidates, int target) {
            List<List<Integer>> res = new ArrayList<>();
            if (candidates == null || candidates.length == 0) {
                return res;
            }
            Arrays.sort(candidates);
            List<Integer> lst = new ArrayList<>();
            helper(res, lst, candidates, target, 0);
            return res;
        }
        
        private void helper(List<List<Integer>> res, List<Integer> lst, int[] candidates, int reminder, int index) {
            if (reminder < 0) {
                return;
            }
            if (reminder == 0) {
                res.add(new ArrayList<>(lst));
            }
            for (int i = index; i < candidates.length; i++) {
    

             //i > index will only skip when numbers before cur is used.
            // i > 0 skip all one combination like [1, 1, 6]

                if(i > index && candidates[i] == candidates[i - 1]) {
                    continue;
                }
                lst.add(candidates[i]);
                helper(res, lst, candidates, reminder - candidates[i], i + 1);
                lst.remove(lst.size() - 1);
            }
        }
    }
  • 相关阅读:
    mysql新建用户的方法
    工具网站
    如何做好站内锚文本?
    js 创建对象与继承
    js tips
    js作用域链 js没有块级作用域
    css
    instanceof
    问题
    传递,引用副本传递
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12123410.html
Copyright © 2011-2022 走看看