zoukankan      html  css  js  c++  java
  • LC.40.Combination Sum II

    https://leetcode.com/problems/combination-sum-ii/description/
    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]
    ]

     1 class Solution {
     2     public List<List<Integer>> combinationSum2(int[] candidates, int target) {
     3         List<List<Integer>> res = new ArrayList<>();
     4         if (candidates == null || candidates.length ==0) {
     5             return res ;
     6         }
     7         //去重复,选代表必须要做的
     8         Arrays.sort(candidates);
     9         List<Integer> sol = new ArrayList<>();
    10         dfs(candidates, target, 0, res, sol);
    11         return res ;
    12     }
    13 
    14     private void dfs(int[] candidates, int remain,int start, List<List<Integer>> res, List<Integer> sol){
    15         //terminate condition
    16         if (remain <= 0) {
    17             if (remain == 0) {
    18                 res.add(new ArrayList(sol));
    19             }
    20             return;
    21         }
    22         for (int i = start ; i < candidates.length; i++) {
    23                 // 1 1' 1''  结果 [1 1'] 和 [1 1‘’] 是一样的,后者跳过
    24                if (i>0 && candidates[i] == candidates[i-1] && i>start) {
    25                  continue ;
    26                }
    27                sol.add(candidates[i]);
    28                //因为一个元素职能用一次,所以必须+1
    29                dfs(candidates, remain-candidates[i], i+1, res, sol);
    30                sol.remove(sol.size()-1);
    31         }
    32     }
    33 }
  • 相关阅读:
    关于JSON可能出现的错误,待更/todo
    mongoose的安装与使用(书签记录) 2017
    HTTP的学习记录3--HTTPS和HTTP
    HTTP的学习记录(二)头部
    HTTP(一)概述
    LeetCode 455. Assign Cookies
    LeetCode 453. Minimum Moves to Equal Array Elements
    LeetCode 448. Find All Numbers Disappeared in an Array
    LeetCode 447. Number of Boomerangs
    LeetCode 416. Partition Equal Subset Sum
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8704454.html
Copyright © 2011-2022 走看看