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 }
  • 相关阅读:
    MicroPython的开发板
    python 安装mysql报错
    30个mysql千万级大数据SQL查询优化技巧详解
    PHP针对数字的加密解密类,可直接使用
    form表单公用
    生成随机邀请码
    Tp5自动验证
    protected和private的区别
    中国俗语大全
    更改Unity项目新建模板
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6388929.html
Copyright © 2011-2022 走看看