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 }
  • 相关阅读:
    SQL中Group By的使用
    SQL 触发器-如何查看当前数据库中有哪些触发器
    调试SQL Server的存储过程及用户定义函数
    SQL判断一个数是整数还是小数
    手动将Excel数据导入SQL
    SQL Case when 的使用方法
    相关资料
    三款大数据工具比拼,谁才是真正的王者
    SQL中CONVERT转化函数的用法
    Sq server 关于存储过程,触发器的一些理论简述
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6388929.html
Copyright © 2011-2022 走看看