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]]
难度:medium
题目:找出所有可能的K个数之和为n的组合,只可以使用1到9之间的数。
注意:所有数都为正,给出的答案中不包含重复的数。
思路:递归
Runtime: 1 ms, faster than 66.65% of Java online submissions for Combination Sum III.
Memory Usage: 35 MB, less than 54.02% of Java online submissions for Combination Sum III.
class Solution {
public List<List<Integer>> combinationSum3(int k, int n) {
List<List<Integer>> result = new ArrayList<>();
if (n > 45 || n < 1 || k < 1 || k > 9) {
return result;
}
combination(1, k, 0, n, new Stack<>(), result);
return result;
}
private void combination(int begin, int k, int sum, int n,
Stack<Integer> stack, List<List<Integer>> result) {
if (k < 0 || sum > n) {
return;
}
if (0 == k && sum == n) {
result.add(new ArrayList<>(stack));
return;
}
for (int i = begin; i <= 9 - k + 1; i++) {
stack.push(i);
combination(i + 1, k - 1, sum + i, n, stack, result);
stack.pop();
}
}
}