Combination Sum III

原创 2015年07月07日 10:55:34
public class Solution {
    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        if (k < 1 || k > 9 || n > (19 - k) * k / 2) {
            return result;
        }
        List<Integer> level = new ArrayList<Integer>();
        dfs(result, level, 1, n, k);
        return result;
    }
    private void dfs(List<List<Integer>> result, List<Integer> level, int start, int sum, int length) {
        if (sum == 0 && level.size() == length) {
            result.add(new ArrayList<Integer>(level));
            return;
        }
        for (int i = start; i <= 9; i++) {
            //剪枝
            if (sum < 0) {
                break;
            }
            if (level.size() > length) {
                break;
            }
            level.add(i);
            dfs(result, level, i + 1, sum - i, length);
            level.remove(level.size() - 1);
        }
    }        
}

相关文章推荐

Leetcode|Combination Sum III[回溯]

Find all possible combinations of k numbers that add up to a number n, given that only numbers from ...

216. Combination Sum III -Medium

Question Find all possible combinations of k numbers that add up to a number n, given that only nu...

leetcode 216. Combination Sum III

class Solution { void do_once(int k,int n, map, int>&candi) { map, int>newcandi; for (map, int...

216. Combination Sum III

Find all possible combinations of k numbers that add up to a number n, given that only numbers from ...

Combination Sum III C#

Find all possible combinations of k numbers that add up to a number n, given that only numbers from ...

LeetCode 216 Combination Sum III(Backtracking)(*)

翻译找出所有的k个数字相加得到数字n的组合,只有1到9的数字可以被使用,并且每个组合间需要是不同的数字集。原文Find all possible combinations of k numbers t...
  • NoMasp
  • NoMasp
  • 2016年07月17日 22:21
  • 1317

LeetCode 216. Combination Sum III 解题报告

LeetCode 216. Combination Sum III 解题报告

leetcode_middle_25_216. Combination Sum III

题意: 给两个数n,k,找出所有n个各不相同的数的和是k的组合。 分析: 其实关键就是搜索遍历,怎么遍历呢?可以这样: 1,2,3    1,2,4    1,2,5  ...   1,2...
  • pusude
  • pusude
  • 2017年02月07日 14:44
  • 80

LeetCode笔记:216. Combination Sum III

寻找k个数相加得到n的所有组合

Leetcode——216. Combination Sum III

题目:Find all possible combinations of k numbers that add up to a number n, given that only numbers fr...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Combination Sum III
举报原因:
原因补充:

(最多只允许输入30个字)