最少元素和为K的子集:深度优先搜索 (DFS) 算法实现
void dfs(vector<int> path, int sum, int start) //求解算法
{
if (sum == k) //满足条件,输出结果
{
if (path.size() < min_num) //更新最小元素个数
{
min_num = path.size();
ans_path = path;
}
return;
}
if (sum > k || start == n) //剪枝:和已经大于k或者已经遍历完所有数,直接返回
return;
path.push_back(a[start]); //选择当前数
dfs(path, sum + a[start], start + 1);
path.pop_back(); //回溯
dfs(path, sum, start + 1); //不选择当前数,继续遍历下一个数
}
原文地址: https://www.cveoy.top/t/topic/oNj3 著作权归作者所有。请勿转载和采集!