描述
给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的数字可以无限制重复被选取。
所有数字(包括 target)都是正整数。解集不能包含重复的组合。
例子:
输入: candidates = [2,3,5], target = 8
输出: [[2,2,2,2],[2,3,3],[3,5]]
思路
DFS+剪枝:先做排序,将大值优先搜索
回溯模板
void dfs(当前路径,所有路径,[合法路径记号,宽度记号(剪枝),...])
{
if(当前路径是否为合法路径判断)
{
所有路径.push_back(当前路径);、
return;
}
if(深度搜索节点提前终止条件(剪枝))
{
深度剪枝操作;
return;
}
for(宽度搜索)
{
当前路径.push_back(当前深度节点);
dfs(当前路径,所有路径,[合法路径记号,宽度记号(剪枝),...]);
当前路径.pop_back();
}
}
代码
// void 回溯func(判断合法路径标记,当前路径,所有合法路径,[宽度剪枝标记,...])
void dfs(std::vector<int>& src, int target, int startIdx, std::vector<int>& curRoute, std::vector<std::vector<int>>& allRoutes)
{
// 合法路径判断(深度终止判断1)
if (target == 0)
{
allRoutes.push_back(curRoute);
return;
}
// 深度剪枝(深度终止判断2)
if (target < 0)
{
return;
}
// 当前深度的宽度搜索 [startIdx,src.size()-1]
for (int wIdx = startIdx; wIdx < src.size(); wIdx++)
{
curRoute.push_back(src[wIdx]);
target -= src[wIdx];
// 深度搜索 [wIdx,src.size()-1]
// e.g. 第一层深度,宽度序号0,下一层深度:如果target没有<0,宽度序号0,1,2...;如果target<0,宽度序号1,2,3...
// 如果没有wIdx标记,则会深度加深时,不改变宽度;如果需要剪枝,则需要变换宽度
dfs(src, target, wIdx, curRoute, allRoutes);
curRoute.pop_back();
target += src[wIdx];
}
}
std::vector<std::vector<int>> combinationSum(std::vector<int>& src, int target)
{
std::vector<std::vector<int>> allRoutes;
if (src.size() == 0) return allRoutes;
// 排序(降序):方便DFS剪枝判断
std::sort(src.begin(), src.end(), std::greater<int>());
std::vector<int> curRoute;
int startIdx = 0;
dfs(src, target, startIdx, curRoute, allRoutes);
return allRoutes;
}