216 Combination Sum iii

时间:2015-05-30 09:16:47   收藏:0   阅读:143
    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        List<Integer> item = new ArrayList<Integer>();
        int sum[] = {0};
        dfs(k, n, res, item, 1, sum);
        return res;
    }
    public void dfs(int k, int n, List<List<Integer>> res, List<Integer> item, int depth, int[] sum) {
        if (item.size() > k || sum[0] > n) return; 
        if (item.size() == k && sum[0] == n) {
            res.add(new ArrayList<Integer>(item));
            return;
        }
        
        for (int i = depth; i <=9; i++) {
            item.add(i);
            sum[0] += i;
            dfs(k, n, res, item, i+1, sum);
            item.remove(item.size() - 1);
            sum[0] -= i;
        }
    }

 

原文:http://www.cnblogs.com/77rousongpai/p/4539783.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!