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);
            }
        }
    }
  • 相关阅读:
    前端html+css标签简介(可能就我自己看的懂-。-)
    python-day43(正式学习)
    python-day42(正式学习)
    python-day40(正式学习)
    python-day39(正式学习)
    python-day38(正式学习)
    python-day37(正式学习)
    python-day31(正式学习)
    python-day30(正式学习)
    python-day29(正式学习)
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12123410.html
Copyright © 2011-2022 走看看