Combination Sum_DFS

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] 

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));
    }

}

 

posted @ 2015-04-04 13:24  微微程序媛  阅读(100)  评论(0编辑  收藏  举报