39. Combination Sum

Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

The same repeated number may be chosen from candidates unlimited number of times.

Note:

All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.

class Solution {
    public List> combinationSum(int[] candidates, int target) {
       List> result = new ArrayList<>();
        if(candidates==null||candidates.length==0){
            return result;
        }
        List subset=new ArrayList<>();
        Arrays.sort(candidates);
        helper(candidates,0,subset,target,result);
        return result;
    }
    
    //递归的定义:在result[startIndex:]中选取和为target的组合,放在subset中,然后整个放到result里
    private void helper(int[] candidates,int startIndex,List subset,int target,List> result){
        if(target==0){
            result.add(new ArrayList<>(subset));
            return;
        }
        //递归的拆解
        for(int i=startIndex;i

你可能感兴趣的:(leetcode)