zoukankan      html  css  js  c++  java
  • 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, a1 ≤ a2 ≤ … ≤ 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] 

    思路

    先对数组进行升序排列,然后在用回溯法BS,这里用的递归调用实现的

     1 public class Solution {
     2     public List<List<Integer>> combinationSum(int[] candidates, int target) {
     3         Arrays.sort(candidates);
     4         List<List<Integer>> result = new ArrayList<List<Integer>>();
     5         getResult(result, new ArrayList<Integer>(), candidates, target, 0);
     6         
     7         return result;
     8     }
     9     
    10     private void getResult(List<List<Integer>> result, List<Integer> cur, int candidates[], int target, int start){
    11         if(target > 0){
    12             for(int i = start; i < candidates.length && target >= candidates[i]; i++){
    13                 cur.add(candidates[i]);
    14                 getResult(result, cur, candidates, target - candidates[i], i);
    15                 cur.remove(cur.size() - 1);
    16             }//for
    17         }//if
    18         else if(target == 0 ){
    19             result.add(new ArrayList<Integer>(cur));
    20         }//else if
    21     }
    22 }
  • 相关阅读:
    app测试点-1
    毕业5年的感悟
    关于游戏外挂
    python-unittest单元测试框架
    python-requests
    http简介
    python基础-发邮件smtp
    python-加密
    4 Python 日期和时间
    5 Python 数据类型—数字
  • 原文地址:https://www.cnblogs.com/luckygxf/p/4239854.html
Copyright © 2011-2022 走看看