首页 > 其他 > 详细

Combination Sum III

时间:2015-05-27 06:17:10      阅读:249      评论:0      收藏:0      [点我收藏+]

dfs 参考I II, 切不要K sum

Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.

Ensure that numbers within the set are sorted in ascending order.


Example 1:

Input: k = 3, n = 7

Output:

 

[[1,2,4]]

 


Example 2:

Input: k = 3, n = 9

Output:

 

[[1,2,6], [1,3,5], [2,3,4]]

  

public class Solution {
    public  List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> res =new ArrayList<List<Integer>>();
        if(k>=10||n>45||n<k) return res;
        dfs(k,n,res,new ArrayList<Integer>(),1);
        return res;
    }
    public void dfs(int k, int t,List<List<Integer>> res, ArrayList<Integer> item, int start ){
        if(t==0){
            if(item.size()==k){
                res.add(new ArrayList<Integer>(item));
            }
            return;
        }
        if(t<0) return;
        for(int i=start;i<10;i++){
            item.add(i);
            dfs(k,t-i,res,item,i+1);
            item.remove(item.size()-1);
        }
        
    }
}

 

Combination Sum III

原文:http://www.cnblogs.com/jiajiaxingxing/p/4532257.html

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