算法小白,最近刷LeetCode。希望能够结合自己的思考和别人优秀的代码,对题目和解法进行更加清晰详细的解释,供大家参考^_^
Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
The same repeated number may be chosen from C unlimited number of times.
Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
For example, given candidate set [2, 3, 6, 7] and target 7,
A solution set is:
[
[7],
[2, 2, 3]
]
给定一个无重复元素的序列和一个目标值,序列中的每个数字可以不使用,或使用多次,输出所有和等于目标值的可行方案。
使用递归方法,首先对元素排序,然后每次选择一个元素0次或a次,从目标值中减去所选择数的和值,再次进行递归,当和值变成0时,说明找到了一个可行方案,当然也要注意不要越界,同时当下一个数字比当前目标值大时,说明当前方案不可行,递归返回。
class Solution {
public:
// 递归函数:candidates是元素集合,diff是当前目标和值,begin是本次要选数字的索引
// tmp为生成序列,res为方案结果集
void fun(const vector<int> &candidates, int diff, int begin, vector<int> tmp, vector<vector<int>> &res) {
if (diff == 0) { res.push_back(tmp); return ; } // 和值为0,说明找到一个可行方案,将该方案加入到结果集中
if (begin == candidates.size()) return ; // 索引越界,返回
if (diff < candidates[begin]) return; // 目标和值小于当前值,该方案不可行,返回
for (int i = 0; i <= diff/candidates[begin]; ++i) { // 选择该元素0次或x次,x<=diff/当前元素值
int ii = i;
vector<int> tmp2(tmp); // 保存当前递归状态,复制一个临时对象作为下次递归的参数
while (ii--) tmp2.push_back(candidates[begin]); // 将其加入到序列中i次
fun(candidates, diff-candidates[begin]*i, begin+1, tmp2, res); // 进行递归
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end()); // 排序
vector<vector<int>> res;
fun(candidates, target, 0, vector<int>{}, res); // 调用递归函数
return res;
}
};