zoukankan      html  css  js  c++  java
  • Leetcode-Combination Sum

    Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

    The same repeated number may be chosen from C unlimited number of times.

    Note:

    • All numbers (including target) will be positive integers.
    • Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1a2 ≤ … ≤ ak).
    • The solution set must not contain duplicate combinations.

    For example, given candidate set 2,3,6,7 and target 7,
    A solution set is:
    [7]
    [2, 2, 3]

    Solution:

    A recursive method.

     1 public class Solution {
     2     public List<List<Integer>> combinationSum(int[] candidates, int target) {
     3         List<List<Integer>> resSet = new ArrayList<List<Integer>>();
     4         List<Integer> curRes = new ArrayList<Integer>();
     5         if (candidates.length==0) return resSet;
     6         Arrays.sort(candidates);
     7         int cur=0,end=candidates.length-1;
     8         for (int i=0;i<candidates.length;i++)
     9             if (candidates[i]>target){
    10                 end = i-1;
    11                 break;         
    12             }
    13          
    14 
    15         sumRecur(candidates,cur,end,target,resSet,curRes);
    16 
    17         return resSet;
    18     }
    19 
    20 
    21     public void sumRecur(int[] candidates, int cur, int end, int valLeft, List<List<Integer>> resSet, List<Integer> curRes){
    22         if (valLeft==0){
    23             List<Integer> temp = new ArrayList<Integer>();
    24             temp.addAll(curRes);
    25             resSet.add(temp);
    26             return;
    27         }
    28 
    29         if (valLeft>= candidates[cur]){
    30             curRes.add(candidates[cur]);
    31             sumRecur(candidates,cur,end,valLeft-candidates[cur],resSet,curRes);
    32             curRes.remove(curRes.size()-1);
    33         }
    34 
    35         if (cur<end){
    36             sumRecur(candidates,cur+1,end,valLeft,resSet,curRes);
    37         }
    38     }
    39 }
  • 相关阅读:
    filter()函数
    递归算法
    日志模块nb_log
    sys.argv[]简单阐述
    DB2中字符、数字和日期类型之间的转换
    Java 连接 Hive的样例程序及解析
    对hadoop namenode -format执行过程的探究
    想要成为牛人、大佬,那请至少拥有这12项技能!
    形象决定你的收入,别问为什么!
    年轻人,能用钱解决的,绝不要花时间(转)
  • 原文地址:https://www.cnblogs.com/lishiblog/p/4111917.html
Copyright © 2011-2022 走看看