原题链接在这里: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:
1 class Solution { 2 public List<List<Integer>> combinationSum3(int k, int n) { 3 List<List<Integer>> res = new ArrayList<List<Integer>>(); 4 if(k<=0 || n<=0){ 5 return res; 6 } 7 8 dfs(k, n, 1, new ArrayList<Integer>(), res); 9 return res; 10 } 11 12 private void dfs(int k, int target, int start, List<Integer> item, List<List<Integer>> res){ 13 if(target == 0 && item.size() == k){ 14 res.add(new ArrayList<Integer>(item)); 15 return; 16 } 17 18 if(target < 0 || item.size() > k){ 19 return; 20 } 21 22 for(int i = start; i<=9; i++){ 23 item.add(i); 24 dfs(k, target-i, i+1, item, res); 25 item.remove(item.size()-1); 26 } 27 } 28 }
AC Python:
1 class Solution: 2 def combinationSum3(self, k: int, n: int) -> List[List[int]]: 3 res = [] 4 self.dfs(k, n, 1, [], res) 5 return res 6 7 def dfs(self, k: int, n: int, start: int, item: List[int], res: List[List[int]]) -> None: 8 if n == 0 and len(item) == k: 9 res.append(item[:]) 10 return 11 12 if(n < 0 or len(item) > k): 13 return 14 15 for i in range(start, 10): 16 item.append(i) 17 self.dfs(k, n - i, i + 1, item, res) 18 item.pop()