题目描述
给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用一次。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/combination-sum-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
样例
示例 1:
输入: candidates = [10,1,2,7,6,1,5], target = 8,
所求解集为:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
示例 2:
输入: candidates = [2,5,2,1,2], target = 5,
所求解集为:
[
[1,2,2],
[5]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/combination-sum-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
算法1
(暴力枚举)
因为数组中有重复的元素,所以要先对数组进行排序,计算出每个数重复cnt
次, 然后需要在dfs
的函数中,循环i
的时候, 加上i <= cnt
条件, 并且,递归的时候下一个数是k
。
时间复杂度
参考文献
C++ 代码
class Solution {
public:
vector<vector<int>> ans;
vector<int> path;
vector<vector<int>> combinationSum2(vector<int>& c, int target) {
sort(c.begin(), c.end());
dfs(c, 0, target);
return ans;
}
void dfs(vector<int> &c, int u, int target){
if (target == 0){
ans.push_back(path);
return;
}
if (u == c.size()) return;
int k = u + 1;
while (k < c.size() && c[k] == c[u]) k ++;
int cnt = k - u;
for (int i = 0; c[u] * i <= target && i <= cnt; i ++){
dfs(c, k, target - c[u] * i);//下一个数开始应该是k开始
path.push_back(c[u]);
}
for (int i = 0; c[u] * i <= target && i <= cnt; i ++)
path.pop_back();
}
};
佬,你这个恢复现场的逻辑我没看懂,等前一个for执行完才恢复?可以解释一下吗?