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

Combination Sum III —— LeetCode

时间:2015-05-29 17:25:09      阅读:112      评论: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]]

题目大意:从1~9找出所有的k个数的组合,使其和等于n。

解题思路:还是回溯,每个数只能出现一次,每次递归都从当前数的下一个开始,当k==0&&n==0,就可以加入结果集。

    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> res = new ArrayList<>();
        Deque<Integer> tmp = new ArrayDeque<>();
        if (n == 0 || k == 0 || n / k > 9) {
            return res;
        }
        helper(res, tmp, 1, k, n);
        return res;
    }

    private void helper(List<List<Integer>> res, Deque<Integer> tmp, int start, int k, int n) {
        if (0 == n && k == 0) {
            res.add(new ArrayList<>(tmp));
//            System.out.println(tmp);
            return;
        }
        for (int i = start; i <= 9; i++) {
            tmp.addLast(i);
            helper(res, tmp, i + 1, k - 1, n - i);
            tmp.removeLast();
        }
    }

 

Combination Sum III —— LeetCode

标签:

原文地址:http://www.cnblogs.com/aboutblank/p/4538926.html

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