LeetCode Combination Sum III

时间:2022-01-23 03:54:34

原题链接在这里:https://leetcode.com/problems/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.

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]]

题解:

Combination Sum II相似,不同的是中不是所有元素相加,只是k个元素相加。

所以在把item的copy 加到res前需要同时满足item.size() == k 和 target == 0两个条件. candidates里没有相同元素,所以res中不可能有duplicates. 因此没有检验去重的步骤。

Time Complexity: exponenetial.

Space: O(1). stack space最多9层.

AC Java:

 class Solution {
public List<List<Integer>> combinationSum3(int k, int n) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if(k<=0 || n<=0){
return res;
} dfs(k, n, 1, new ArrayList<Integer>(), res);
return res;
} private void dfs(int k, int target, int start, List<Integer> item, List<List<Integer>> res){
if(target == 0 && item.size() == k){
res.add(new ArrayList<Integer>(item));
return;
} if(target < 0 || item.size() > k){
return;
} for(int i = start; i<=9; i++){
item.add(i);
dfs(k, target-i, i+1, item, res);
item.remove(item.size()-1);
}
}
}

跟上Combination Sum IV.