Find all valid combinations of k
numbers that sum up to n
such that the following conditions are true:
- Only numbers
1
through9
are used. - Each number is used at most once.
Return a list of all possible valid combinations. The list must not contain the same combination twice, and the combinations may be returned in any order.
Example 1:
Input: k = 3, n = 7 Output: [[1,2,4]] Explanation: 1 + 2 + 4 = 7 There are no other valid combinations.
Example 2:
Input: k = 3, n = 9 Output: [[1,2,6],[1,3,5],[2,3,4]] Explanation: 1 + 2 + 6 = 9 1 + 3 + 5 = 9 2 + 3 + 4 = 9 There are no other valid combinations.
Example 3:
Input: k = 4, n = 1 Output: [] Explanation: There are no valid combinations. [1,2,1] is not valid because 1 is used twice.
Example 4:
Input: k = 3, n = 2 Output: [] Explanation: There are no valid combinations.
Example 5:
Input: k = 9, n = 45 Output: [[1,2,3,4,5,6,7,8,9]] Explanation: 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 = 45 There are no other valid combinations.
Constraints:
2 <= k <= 9
1 <= n <= 60
DFS.
class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
def dfs(i, s, t):
if i > 9 or s > n or len(t) > k:
return
if s == n and len(t) == k:
ans.append(t[:])
return
i += 1
t.append(i)
dfs(i, s + i, t)
t.pop()
dfs(i, s, t)
ans = []
dfs(0, 0, [])
return ans
class Solution {
private List<List<Integer>> ans;
public List<List<Integer>> combinationSum3(int k, int n) {
ans = new ArrayList<>();
dfs(0, n, k, new ArrayList<>());
return ans;
}
private void dfs(int i, int n, int k, List<Integer> t) {
if (i > 9 || n < 0 || t.size() > k) {
return;
}
if (n == 0 && t.size() == k) {
ans.add(new ArrayList<>(t));
return;
}
++i;
t.add(i);
dfs(i, n - i, k, t);
t.remove(t.size() - 1);
dfs(i, n, k, t);
}
}
class Solution {
public:
vector<vector<int>> ans;
vector<vector<int>> combinationSum3(int k, int n) {
vector<int> t;
dfs(0, n, k, t);
return ans;
}
void dfs(int i, int n, int k, vector<int>& t) {
if (i > 9 || n < 0 || t.size() > k) return;
if (n == 0 && t.size() == k)
{
ans.push_back(t);
return;
}
++i;
t.push_back(i);
dfs(i, n - i, k, t);
t.pop_back();
dfs(i, n, k, t);
}
};
func combinationSum3(k int, n int) [][]int {
var ans [][]int
var t []int
var dfs func(i, n int, t []int)
dfs = func(i, n int, t []int) {
if i > 9 || n < 0 || len(t) > k {
return
}
if n == 0 && len(t) == k {
cp := make([]int, len(t))
copy(cp, t)
ans = append(ans, cp)
return
}
i++
t = append(t, i)
dfs(i, n-i, t)
t = t[:len(t)-1]
dfs(i, n, t)
}
dfs(0, n, t)
return ans
}