leetcode--Combination Sum

来源:互联网 发布:广联达翻样软件多少钱 编辑:程序博客网 时间:2024/05/21 20:42

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 (a1a2, … , 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]
[java] view plain copy
  1. public class Solution {  
  2.     public List<List<Integer>> combinationSum(int[] candidates, int target) {  
  3.         List<List<Integer>> res = new ArrayList<List<Integer>>();  
  4.         Arrays.sort(candidates);  
  5.         Stack<Integer> stack = new Stack<Integer>();  
  6.         dfs(res, stack, target, 0, candidates,0);  
  7.         return res;  
  8.     }  
  9.       
  10.     void dfs(List<List<Integer>> res,Stack<Integer> stack,int target,int cur,int[] arr,int sum){        
  11.         if(sum==target){  
  12.             ArrayList<Integer> data = new ArrayList<Integer>(stack);  
  13.             res.add(data);  
  14.             return;  
  15.         }else if(sum>target) return;  
  16.         else{  
  17.             for(int i=cur;i<arr.length;i++){  
  18.                 stack.add(arr[i]);  
  19.                 sum += arr[i];  
  20.                 dfs(res, stack, target, i, arr,sum);  
  21.                 sum -= arr[i];  
  22.                 stack.pop();  
  23.             }  
  24.         }  
  25.     }  
  26. }  

原文链接http://blog.csdn.net/crazy__chen/article/details/45725483

原创粉丝点击