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]]
给出整数k和n,找到从1到9中可以使和为n的k个数
思路:
DFS
使用过的数字压入栈,当栈中数字和为n且个数为k时即满足一组解,用完一个数字后出栈,再进入下一个数字,从左到右
当n为0且栈中已有k个数字时,证明不需要再加入新的数字且已满足一组解,将解保存到结果list中
class Solution {
public List<List<Integer>> combinationSum3(int k, int n) {
List<List<Integer>> result = new ArrayList<>();
Stack<Integer> st = new Stack<>();
combination(1, st, k, n, result);
return result;
}
void combination(int start, Stack<Integer> st, int k, int target, List<List<Integer>> result) {
if(st.size() == k && target == 0) {
result.add(new ArrayList<Integer>(st));
return;
}
if(st.size() > k || target < 0) {
return;
}
for(int i = start; i <= 9; i++) {
st.push(i);
combination(i+1, st, k, target-i, result);
st.pop();
}
}
}