• leetcode------Combination Sum II


    标题: Combination Sum II
    通过率: 25.1%
    难度: 中等

    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.
    • Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
    • 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] 

    与第一个版本不同的是set中的元素不能重复使用,那么递归时起始位置就要+1操作了代码如下:

     1 public class Solution {
     2     public ArrayList<ArrayList<Integer>> combinationSum2(int[] num, int target) {
     3         ArrayList<ArrayList<Integer>> res=new ArrayList<ArrayList<Integer>>();
     4         ArrayList<Integer> tmp=new ArrayList<Integer>();
     5         Arrays.sort(num);
     6         dfs(num,target,0,res,tmp);
     7         return res;
     8     }
     9     public void dfs(int[] num, int target,int start,ArrayList<ArrayList<Integer>> res,ArrayList<Integer> tmp){
    10         if(target<0)return;
    11         if(target==0 && !res.contains(tmp)){
    12             res.add(new ArrayList<Integer>(tmp));
    13             return ;
    14         }
    15         for(int i=start;i<num.length;i++){
    16             tmp.add(num[i]);
    17             dfs(num,target-num[i],i+1,res,tmp);
    18             tmp.remove(tmp.size()-1);
    19         }
    20     }
    21 }
  • 相关阅读:
    针对性博文
    spring事务
    Redis_主从模式_哨兵模式_Cluster集群模式
    Redis AOF、RDB持久化
    Redis 高可用分布式集群
    Redis 基础
    Oracle优化学习
    Mysql:索引实战
    Mysql:性能优化
    js 二维数组定义
  • 原文地址:https://www.cnblogs.com/pkuYang/p/4354384.html
Copyright © 2020-2023  润新知