首页 > 其他 > 详细

Combination Sum

时间:2015-01-21 19:50:34      阅读:245      评论:0      收藏:0      [点我收藏+]

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 }

 

Combination Sum

原文:http://www.cnblogs.com/luckygxf/p/4239854.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!