原題連接在這裏:https://leetcode.com/problems/combination-sum-iii/html
題目:post
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.url
Ensure that numbers within the set are sorted in ascending order.spa
Example 1:code
Input: k = 3, n = 7htm
Output:blog
[[1,2,4]]
Example 2:leetcode
Input: k = 3, n = 9rem
Output:get
[[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 }