当前位置:网站首页>Interview must brush algorithm top101 backtracking article top34
Interview must brush algorithm top101 backtracking article top34
2022-07-06 00:49:00 【A thief who surrendered himself】
A combination containing a collection of repeating elements
Title source :(leetcode)[https://leetcode.cn/problems/4sjJUc/]
1、 Title Description
Given an array of integers that may have duplicate numbers candidates And a target number target , find candidates All can make numbers and target The combination of .
candidates Each number in can only be used once in each combination , A solution set cannot contain duplicate combinations .
2、 Thinking analysis
Train of thought :DFS
The output data of the example is ordered, so the first thing is to sort the data , Then call DFS Recursive traversal of functions produces every result that appears there , When the condition is met, it will be added to the result array , But there is a problem because it contains repeated arrays , Therefore, repeated arrays are bound to appear in structural data , So it's going to be heavy ,find If the function cannot be found, it will be inserted into the data, but because it needs to be judged every time it is inserted into the array, the time complexity increases .
Train of thought two : to flash back + recursive
We use it dfs( pos,rest) Represents a recursive function , among pos Indicates that we are currently recursive to the array candidates No pos Number , and rest We also need to choose and for rest Put the number of into the list as a combination ;
For the current second pos Number , We can do it two ways : Choose or not . If we choose this number , So we call dfs(pos+ 1, rest - candidateslpos) Recursion , Note that there must be rest ≥ candidates[pos). If we don't choose this number , So we call dfs(pos+ 1, rest) Recursion ;
Before a recursion begins , If rest The value of is 0, That means we found a sum for target The combination of , Put it in the answer . Before each call to a recursive function , If we choose that number , You need to put it at the end of the list , This list stores all the numbers we selected . In backtracking , If we choose that number , To remove it from the end of the list .
3、 Code implementation
class Solution {
public:
void func(vector<vector<int>> &v,vector<int>&vm,int &&sum,
vector<int>&nums,vector<int> num,int target,int &&index){
if(sum>=target){
if(sum==target){
if(find(v.begin(),v.end(),vm)==v.end()){
v.push_back(vm);
}
}
return;
}
for(int i=index;i<nums.size();i++){
if(num[i]==0){
num[i]=1;
vm.push_back(nums[i]);
func(v,vm,sum+nums[i],nums,num,target,i+1);
num[i]=0;
vm.pop_back();
}
}
}
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(),candidates.end());
vector<vector<int>> v;
vector<int> vs;
vector<int> num(candidates.size(),0);
int inex=0;
func(v,vs,0,candidates,num,target,0);
return v;
}
};
class Solution {
private:
vector<pair<int, int>> freq;
vector<vector<int>> ans;
vector<int> sequence;
public:
void dfs(int pos, int rest) {
if (rest == 0) {
ans.push_back(sequence);
return;
}
if (pos == freq.size() || rest < freq[pos].first) {
return;
}
dfs(pos + 1, rest);
int most = min(rest / freq[pos].first, freq[pos].second);
for (int i = 1; i <= most; ++i) {
sequence.push_back(freq[pos].first);
dfs(pos + 1, rest - i * freq[pos].first);
}
for (int i = 1; i <= most; ++i) {
sequence.pop_back();
}
}
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
for (int num: candidates) {
if (freq.empty() || num != freq.back().first) {
freq.emplace_back(num, 1);
} else {
++freq.back().second;
}
}
dfs(0, target);
return ans;
}
};
Full Permutation without duplicate element set
Title source :leetcode
1、 Problem description :
Given an array of integers without duplicate numbers nums , Back to its All possible permutations . Sure In any order Return to the answer .
2、 Thinking analysis
Careful observation shows that , The problem of finding different full permutations can be accomplished by exchanging array elements ;
If the array length is n, Exchange the first element with each subsequent element separately , Generate n Different full permutations ; Then the second element is exchanged with each subsequent element , Generate n -1 Different full permutations
3、 Code implementation
class Solution {
public:
void func(vector<vector<int>> &v,vector<int> &vm,vector<int>&nums,vector<int>&num){
if(vm.size()==nums.size()){
v.push_back(vm);
return;
}
for(int i=0;i<nums.size();i++){
if(num[i]==0){
num[i]=1;
vm.push_back(nums[i]);
func(v,vm,nums,num);
vm.pop_back();
num[i]=0;
}
}
}
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int>> v;
vector<int> vm;
vector<int>num(nums.size(),0);
func(v,vm,nums,num);
return v;
}
};
边栏推荐
- [groovy] compile time metaprogramming (compile time method injection | method injection using buildfromspec, buildfromstring, buildfromcode)
- The relationship between FPGA internal hardware structure and code
- Leetcode:20220213 week race (less bugs, top 10% 555)
- 【线上小工具】开发过程中会用到的线上小工具合集
- logstash清除sincedb_path上传记录,重传日志数据
- 程序员搞开源,读什么书最合适?
- Common API classes and exception systems
- [groovy] JSON serialization (convert class objects to JSON strings | convert using jsonbuilder | convert using jsonoutput | format JSON strings for output)
- Leetcode 450 deleting nodes in a binary search tree
- An understanding of & array names
猜你喜欢

Problems and solutions of converting date into specified string in date class

Notepad++ regular expression replacement string

95后CV工程师晒出工资单,狠补了这个,真香...
![Cf:d. insert a progression [about the insert in the array + the nature of absolute value + greedy top-down]](/img/9e/c933f454a39d906a407e4d415f0b87.png)
Cf:d. insert a progression [about the insert in the array + the nature of absolute value + greedy top-down]

《强化学习周刊》第52期:Depth-CUPRL、DistSPECTRL & Double Deep Q-Network

Data analysis thinking analysis methods and business knowledge - analysis methods (III)

小程序技术优势与产业互联网相结合的分析

Comment faire votre propre robot

For a deadline, the IT fellow graduated from Tsinghua suddenly died on the toilet

notepad++正則錶達式替換字符串
随机推荐
【线上小工具】开发过程中会用到的线上小工具合集
Hundreds of lines of code to implement a JSON parser
VSphere implements virtual machine migration
Notepad++ regular expression replacement string
Pointer - character pointer
Basic introduction and source code analysis of webrtc threads
数据分析思维分析方法和业务知识——分析方法(二)
vSphere实现虚拟机迁移
Common API classes and exception systems
新手入门深度学习 | 3-6:优化器optimizers
curlpost-php
cf:D. Insert a Progression【关于数组中的插入 + 绝对值的性质 + 贪心一头一尾最值】
几百行代码实现一个 JSON 解析器
[groovy] compile time metaprogramming (compile time method interception | find the method to be intercepted in the myasttransformation visit method)
MCU realizes OTA online upgrade process through UART
notepad++正則錶達式替換字符串
Curlpost PHP
Cf:h. maximum and [bit operation practice + K operations + maximum and]
Room cannot create an SQLite connection to verify the queries
The value of applet containers