zoukankan      html  css  js  c++  java
  • 40. 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]
    ]
    

    本题让我对这一系列题目又有了新的感觉,先说区别,本题前面计算过的数组元素,后面的元素计算的时候就不需要回来把之前的元素加上了,也就是说,相当于小卒一去不回头的感觉,它和combination sum1的区别最大的就是会不会包含它本身。代码如下:

     1 public class Solution {
     2     public List<List<Integer>> combinationSum2(int[] candidates, int target) {
     3         List<List<Integer>> res = new ArrayList<>();
     4         Arrays.sort(candidates);
     5         backtracking(res,candidates,target,new ArrayList<Integer>(),0);
     6         return res;
     7     }
     8     public void backtracking(List<List<Integer>> res,int[] candidates,int target,List<Integer> list,int start){
     9         if(target==0){
    10             res.add(new ArrayList<Integer>(list));
    11         }else if(target<0) return;
    12         else{
    13             for(int i=start;i<candidates.length;i++){
    14                 if(i>start&&candidates[i]==candidates[i-1]){
    15                     continue;
    16                 }
    17                 list.add(candidates[i]);
    18                 backtracking(res,candidates,target-candidates[i],list,i+1);
    19                 list.remove(list.size()-1);
    20             }
    21         }
    22     }
    23 }
  • 相关阅读:
    项目笔记三
    ASP.NET小收集<9>:HTML解析
    TSQL数据维护:更改表所有者
    [转贴]SQL2005:数据类型最大值
    TSQL存储过程:ROW_NUMBER()分页
    JS收集<7>:浏览器event兼容
    统计SQLServer2005表记录数
    ASP.NET小收集<8>:JS创建对象
    JS收集<8>:HTML控件的坐标
    MySql按指定天数进行分组数据统计分析 1
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6388929.html
Copyright © 2011-2022 走看看