39. Combination Sum

import java.util.*;

public class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        
        int size=candidates.length;
        
        List<List<Integer>> res=new ArrayList<List<Integer>>();
        
        List<Integer> temp=new ArrayList<Integer>();
        
        sum(candidates,target,size,0,0,temp,res);

        return res;
        
        
        
    }
    
    public static void sum(int[] candidates,int target,int size,int sum,int index,List<Integer> temp,List<List<Integer>> res)
    {
        if(sum==target)
        {
            //表示找到了目标的数组
            //将temp压入res
            List<Integer> element=new ArrayList<Integer>();
            for(int j=0;j<temp.size();j++)
                element.add(temp.get(j));
            res.add(element);
        }
        else if(sum>target)
        {
            //表示超过了界限,直接退出就好
            return ;
        }
        else
        {
            //从index开始,每个都入一遍
            for(int i=index;i<size;i++)
            {
                sum+=candidates[i];
                temp.add(candidates[i]);
                sum(candidates,target,size,sum,i,temp,res);
                sum-=candidates[i];
                temp.remove(temp.size()-1);
            }
        }
    }
    
   
    
}

 

posted @ 2016-07-07 14:34  阿怪123  阅读(119)  评论(0)    收藏  举报