216. 组合总和 III

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

说明:

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

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

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/combination-sum-iii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 1 public class Solution {
 2     private List<List<Integer>> res = null;
 3     private List<Integer> subset = null;
 4 
 5     // 第cnt个数
 6     private void helper(int cur, int cnt, int sum, int k, int n){
 7         for (int i = cur; i < 10; i++) {
 8             if (sum+i > n)
 9                 break;
10             subset.add(i);
11             if (i+1 < 10 && cnt+1 <= k)
12                 helper(i+1, cnt+1, sum+i, k,n);
13             if (cnt == k && sum+i == n)
14                 res.add(new ArrayList<>(subset));
15             subset.remove(subset.size()-1);
16         }
17     }
18 
19     public List<List<Integer>> combinationSum3(int k, int n) {
20         res = new ArrayList<>();
21         subset = new ArrayList<>();
22         helper(1, 1, 0, k, n);
23         return res;
24     }
25 
26     public static void main(String[] args) {
27         List<List<Integer>> lists = new Solution().combinationSum3(3, 15);
28         for (List<Integer> e : lists) {
29             System.out.println(e);
30         }
31     }
32 }
原文地址:https://www.cnblogs.com/yfs123456/p/11617673.html