zoukankan      html  css  js  c++  java
  • 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);
            }
        }
    }
    

      

  • 相关阅读:
    Httpclient5工具类
    temp
    《On Java 8》笔记 2
    《On Java 8》笔记
    《Effective Java》笔记 4~5
    Oracle数据库对比MySQL
    《Effective Java》笔记
    [BUAA2021软工]结对第一阶段博客作业小结
    Spring Boot入门
    MyBatis入门
  • 原文地址:https://www.cnblogs.com/superzhaochao/p/6436196.html
Copyright © 2011-2022 走看看