首页 > 其他 > 详细

Combination SumIII; BackTracking; Array;

时间:2016-03-01 06:21:40      阅读:187      评论:0      收藏:0      [点我收藏+]

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);
        }
    }
    
}

 

Combination SumIII; BackTracking; Array;

原文:http://www.cnblogs.com/5683yue/p/5229563.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!