Leetcode combination sum

题目地址:https://leetcode.com/problems/combination-sum/

题目分析:采用递归方式,先将数组排序,依次遍历数组中元素,如果target比第i个元素大则加入到结果集中,如果比第i个元素小返回;如果target为0,将组合加入到返回值中。

题目解答:

import java.util.ArrayList;
import java.util.Arrays;

public class Solution {
    public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) {
        ArrayList<Integer> curr = new ArrayList<Integer>();
        ArrayList<ArrayList<Integer>> ret = new ArrayList<ArrayList<Integer>>();
        
        if(candidates == null || candidates.length == 0 || target == 0){
            return ret;
        }
        
        Arrays.sort(candidates);
        combinationSum(candidates,0,target,curr,ret);
        return ret;
    }
    
    public void combinationSum(int[] candidates,int start,int target,ArrayList<Integer> curr,ArrayList<ArrayList<Integer>> ret){
        if(target == 0){
            ArrayList<Integer> temp = new ArrayList<Integer>(curr);
            ret.add(temp);
            return;
        }
        
        for(int i = start;i<candidates.length;i++){
            if(target < candidates[i]){
                return;
            }
            
            curr.add(candidates[i]);
            combinationSum(candidates,i,target-candidates[i],curr,ret);
            curr.remove(curr.size()-1);
        }
        return;
    }
}

 

posted @ 2015-04-13 00:35  buptubuntu  阅读(116)  评论(0)    收藏  举报