首页 > 其他 > 详细

Combination Sum

时间:2014-02-06 16:28:38      阅读:410      评论: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.

bubuko.com,布布扣
 1 public class Solution {
 2         public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) {
 3             ArrayList<Integer> output= new ArrayList<Integer>();
 4             ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
 5             if(candidates.length<=0) return res;
 6             Arrays.sort(candidates);//don‘t forget sort
 7             DFS(res,output,0,candidates,0,target);
 8             return res;
 9         }
10         public void DFS(ArrayList<ArrayList<Integer>>res,ArrayList<Integer> output,int start,int[]can,int sum,int target){
11             if(sum>target) return;
12             if(sum==target){
13                 ArrayList<Integer> temp = new ArrayList<Integer>();
14                 temp.addAll(output);
15                 res.add(temp);
16                 return;
17             }
18             for(int i=start;i<can.length;i++){
19                 sum +=can[i];
20                 output.add(can[i]);
21                 DFS(res,output,i,can,sum,target);
22                 sum-=output.get(output.size()-1);
23                 output.remove(output.size()-1);
24             }
25         }
26     }
View Code

Combination Sum

原文:http://www.cnblogs.com/krunning/p/3538739.html

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