Note that when you put the list to be the parameter, and each time you do the recursion, you add element into the list, you need to remove the former added elements in the previous combination.

Code:

public class Solution {
    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> ret = new ArrayList<>();
        List<Integer> list = new ArrayList<>();
        combination(list, ret, k, n, 0, 1);
        return ret;
    }
    
    public void combination(List<Integer> list, List<List<Integer>> ret, int k, int remain, 
                int last, int index){
        if(remain < last+1) return;
        if(index == k){
            if(remain > 9) return;
            list.add(remain);
            ret.add(new ArrayList(list));
            list.remove(list.size()-1);
            return;
        }
        for(int i = last+1; i <= remain && i <= 9; i++){
                //if(!status) break;
                if(index == 1) list = new ArrayList<>();
                list.add(i);
                combination(list, ret, k, remain-i, i, index+1);
                list.remove(list.size()-1);
        }
    }
    
}

 

posted on 2016-03-01 05:23  爱推理的骑士  阅读(158)  评论(0编辑  收藏  举报