leetcode Combination Sum

题目链接

思路:
递归回溯

public class Solution {
    int [] candidates;
    int n;
    LinkedList<List<Integer>> result;
    LinkedList<Integer>temp;
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        this.candidates=candidates;
        n=candidates.length;
        result=new LinkedList<List<Integer>>();
        temp=new LinkedList<Integer>();
        help(0,target);
        return result;
    }

    void help(int start,int left)
    {
        for(int i=start;i<n;i++)
        {
            int currentLeft=left-candidates[i];
            if(currentLeft<0)
            {
                continue;
            }


            temp.add(candidates[i]);
            if(currentLeft>0)
            {
                help(i,currentLeft);
            }
            else// if(currentLeft==0)
            {
                result.add(new LinkedList<Integer>(temp));
            }
            temp.removeLast();

        }
        return;
    }
}

你可能感兴趣的:(leetcode Combination Sum)