标签:
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:
For example, given candidate set 2,3,6,7
and target 7
,
A solution set is: [7]
[2, 2, 3]
package leetcode2; import java.util.*; public class combaniation_sum { public static ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) { ArrayList<ArrayList<Integer>> res=new ArrayList<ArrayList<Integer>>(); ArrayList<Integer> mem=new ArrayList<Integer>(); Arrays.sort(candidates); dfs(res,mem,0,candidates,target); // dfs模版!!一定要记住! return res; } public static void dfs(ArrayList<ArrayList<Integer>> res,ArrayList<Integer> mem, int deep, int[] candidates, int target) { // TODO Auto-generated method stub if(target<0){ return; } if (target==0){ if(!res.contains(mem)){ res.add(new ArrayList<Integer>(mem)); } } for(int i=deep;i<candidates.length;i++){ mem.add(candidates[i]); int retaget=target-candidates[i]; dfs(res,mem,i,candidates,retaget) ; if(mem.size()>0) mem.remove(mem.size()-1); } } public static void main(String[] args) { // TODO Auto-generated method stub int[] s={2,3,6,7}; System.out.println(combinationSum(s,7)); } }
标签:
原文地址:http://www.cnblogs.com/joannacode/p/4392038.html