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]]
DFS+剪枝,注意顺序是递增的。且最大不会大于9.
class Solution {
public:
vector<vector<int>> combinationSum3(int k, int n) {
vector<int> ret;
vector<vector<int>> ans;
dfs(ans,ret,0,k,n);
return ans;
}
void dfs(vector<vector<int>> &ans,vector<int> &ret,int start,int k,int n){
if(n<((2*start+k+1)*k/2) || n>((19-k)*k/2)) //剪枝加快搜索速度
return;
if(k==0){
if(n==0) ans.push_back(ret);
return ;
}
for(int i=start+1; i<=9; ++i){
ret.push_back(i);
dfs(ans,ret,i,k-1,n-i);
ret.pop_back();
}
}
};
本文探讨了一种使用深度优先搜索(DFS)结合剪枝技术来解决组合数学问题的方法,目标是在1到9的数字中找到所有可能的k个数组合,使得这些数的和等于给定的n。文章通过实例演示了如何在确保数字升序排列的情况下,高效地找出所有符合条件的唯一数集。重点在于算法优化,通过剪枝技术减少不必要的搜索路径,提高效率。
484

被折叠的 条评论
为什么被折叠?



