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 }
  • 相关阅读:
    Spring MVC- 表单提交
    Ajax提交与传统表单提交的区别说明
    CSS各种居中方法
    Android RecyclerView 使用完全解析 体验艺术般的控件
    如何解决VMware上MAC虚拟机不能上网问题
    input标签的hidden属性的应用及作用
    SpringMVC表单标签简介
    EL显示List里嵌套map(Spring MVC3)返回的model
    Spring3 MVC请求参数获取的几种方法
    写数据到文件,并同步到磁盘
  • 原文地址:https://www.cnblogs.com/lishiblog/p/4111917.html
Copyright © 2011-2022 走看看