码迷,mamicode.com
首页 > 其他好文 > 详细

[leedcode 216] Combination Sum III

时间:2015-08-06 21:50:40      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:

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 {
    List<List<Integer>> res;
    List<Integer> seq;
    public List<List<Integer>> combinationSum3(int k, int n) {
        //dfs,for循环和递归叠加。
        //需要保存level值,因为结果要求是递增的,同时为了确保是k个数,每一次递归,k要减一
        res=new ArrayList<List<Integer>>();
        seq=new ArrayList<Integer>();
        dfs(k,n,1,0);
        return res;
    }
    public void dfs(int k,int n,int start,int sum){
        if(sum==n&&k==0){
            res.add(new ArrayList<Integer>(seq));
        }else if(sum>n||k<=0) return;
        for(int i=start;i<=9;i++){
            seq.add(i);
            dfs(k-1,n,i+1,sum+i);
            seq.remove(seq.size()-1);
        }
    }
}

 

[leedcode 216] Combination Sum III

标签:

原文地址:http://www.cnblogs.com/qiaomu/p/4709205.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!