[LeetCode] 216. Combination Sum III

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.

Note:

  • All numbers will be positive integers.
  • The solution set must not contain duplicate combinations.

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 个数字 使得这k个数字的和等于n
做法最先想到的就是回溯法了,因为是1-9 不重复的选取,可以看作1-9已经是排好序的,递归回溯判断即可

Java代码
 1 class Solution {
 2 
 3     public List<List<Integer>> combinationSum3(int k, int n) {
 4         List<List<Integer>> res = new ArrayList<List<Integer>>();
 5         List<Integer> cur = new ArrayList<>();
 6         sovle(res, cur, 0, k, n, 0);
 7         return res;
 8     }
 9 
10     private void sovle(List<List<Integer>> res, List<Integer> cur, int sum, int k, int n, int lev) {
11         if (sum == n && k == 0) {
12             res.add(cur);
13             return;
14         }
15         if (sum > n || k < 0)
16             return;
17         for (int i = lev; i <= 9; i++) {
18             cur.add(i);
19             sovle(res, cur, sum+i, k-1, n, i + 1);
20             cur.remove(cur.size() - 1);
21         }
22     }
23 }
原文地址:https://www.cnblogs.com/Moriarty-cx/p/9581893.html