• [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);
            }
        }
    }
  • 相关阅读:
    算法训练 2的次幂表示
    算法训练 进制转换
    算法训练 Beaver's Calculator (蓝桥杯)
    抽签问题(不断优化)
    矩阵快速幂
    斐波那契数列
    找出最小自然数N,使N!在十进制下包含Q个0(输入Q,输出N)
    二维数组名是指针的指针吗?
    StringBuffer
    Lake Counting (POJ No.2386)
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12123410.html
Copyright © 2020-2023  润新知