my-leetcode-logs-20230817

Last updated on 2023年8月29日 上午

(复习)40. 组合总和 II(C++回溯算法实现)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class Solution {
public:
//定义两个数组
vector<vector<int>> result;
vector<int> path;

//定义回溯函数
void backtracing(vector<int>& candidates, int target, int sum, int startIndex,vector<bool>& used){
if(sum ==target){
result.push_back(path);
return;
}

//单层循环逻辑
for(int i = startIndex;i < candidates.size() && sum + candidates[i] <= target;i++){

if(i > 0 && candidates[i] == candidates[i-1] && used[i - 1]==false){
continue;//表示树的同层中的上一个一样的元素使用过了
}

sum += candidates[i];
path.push_back(candidates[i]);
used[i] = true;
backtracing(candidates, target, sum, i + 1, used);
used[i] = false;
sum -= candidates[i];
path.pop_back();
}
}


vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
//实现了函数中间
result.clear();
path.clear();
vector<bool> used(candidates.size(), false);
sort(candidates.begin(), candidates.end());
backtracing(candidates, target, 0, 0, used);
return result;
}
};

my-leetcode-logs-20230817
https://thewangyang.github.io/2023/08/17/leetcode-notes-20230817/
Author
wyy
Posted on
2023年8月17日
Updated on
2023年8月29日
Licensed under