• leetcode : combination sum II


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

    Each number in C 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.

    For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8
    A solution set is: 

    [
      [1, 7],
      [1, 2, 5],
      [2, 6],
      [1, 1, 6]
    ]
    
    public class Solution {
        public List<List<Integer>> combinationSum2(int[] candidates, int target) {
            List<List<Integer>> result = new ArrayList<List<Integer>>();
            if(candidates == null || candidates.length == 0) {
                return result;
            }
            List<Integer> list = new ArrayList<Integer>();
            Arrays.sort(candidates);
            helper(result, list, candidates, 0, target);
            return result;
        }
        
        public void helper(List<List<Integer>> result, List<Integer> list, int[] nums, int position, int remain) {
            if(remain < 0) {
                return;
            }
            if(remain == 0) {
                result.add(new ArrayList<Integer>(list));
            }
            for(int i = position; i < nums.length; i++) {
                if(i > position && nums[i] == nums[i - 1]) {
                    continue;
                }
                list.add(nums[i]);
                helper(result, list, nums, i + 1, remain - nums[i]);
                list.remove(list.size() - 1);
            }
        }
    }
    

      

  • 相关阅读:
    CS round--36
    Vijos 1002 过河 dp + 思维
    汇编模拟36选7
    1137
    E. Mike and Foam 容斥原理
    Even-odd Boxes hackerrank 分类讨论
    112. 作业之地理篇 最小费用最大流模板题
    1550: Simple String 最大流解法
    Sam's Numbers 矩阵快速幂优化dp
    java.sql.SQLSyntaxErrorException: ORA-01722: 无效数字
  • 原文地址:https://www.cnblogs.com/superzhaochao/p/6436196.html
Copyright © 2020-2023  润新知