leetcode 216. 组合总和 III java

题目:

找出所有相加之和为 的 个数的组合组合中只允许含有 1 - 9 的正整数,并且每种组合中不存在重复的数字。

说明:

  • 所有数字都是正整数。
  • 解集不能包含重复的组合。 

示例 1:

输入: k = 3, n = 7
输出: [[1,2,4]]

示例 2:

输入: k = 3, n = 9
输出: [[1,2,6], [1,3,5], [2,3,4]]

解题:

class Solution {
    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> res = new ArrayList<>();
        //List<Integer> cur = new ArrayList<>();
        helper(res, new ArrayList<>(), k, n, 1);
        return res;
    }
    
    private void helper(List<List<Integer>> res, List<Integer> cur, int k, int target,
                       int start)
    {
        // exit condition
        if (target == 0 && k == 0)
            res.add(new ArrayList<Integer>(cur));
        else
        {
            for (int i = start; i < 10; i++)
            {
                // prune
                if (target < i) continue;
                else
                {
                    cur.add(i);
                    // set next to i + 1 to avoid duplicate
                    helper(res, cur, k - 1, target - i, i + 1);
                    cur.remove(cur.size() - 1);
                }
            }
        }
    }
}

 

posted @ 2019-05-15 16:31  yanhowever  阅读(355)  评论(0编辑  收藏  举报