当前位置:网站首页>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;
}
};
边栏推荐
- 程序员搞开源,读什么书最合适?
- 如何制作自己的机器人
- A preliminary study of geojson
- China Taiwan strategy - Chapter 8: digital marketing assisted by China Taiwan
- XML Configuration File
- Intranet Security Learning (V) -- domain horizontal: SPN & RDP & Cobalt strike
- Keepalive component cache does not take effect
- Novice entry depth learning | 3-6: optimizer optimizers
- Introduction of motor
- MYSQL GROUP_ The concat function realizes the content merging of the same ID
猜你喜欢
Spark AQE
How to make your own robot
Set data real-time update during MDK debug
Starting from 1.5, build a micro Service Framework - call chain tracking traceid
Problems and solutions of converting date into specified string in date class
MySQL storage engine
Meta AI西雅图研究负责人Luke Zettlemoyer | 万亿参数后,大模型会持续增长吗?
Leetcode 450 deleting nodes in a binary search tree
数据分析思维分析方法和业务知识——分析方法(二)
MCU realizes OTA online upgrade process through UART
随机推荐
Arduino hexapod robot
How to make your own robot
Novice entry depth learning | 3-6: optimizer optimizers
NLP text processing: lemma [English] [put the deformation of various types of words into one form] [wet- > go; are- > be]
Power query data format conversion, Split Merge extraction, delete duplicates, delete errors, transpose and reverse, perspective and reverse perspective
Spark AQE
Leetcode 450 deleting nodes in a binary search tree
Room cannot create an SQLite connection to verify the queries
cf:D. Insert a Progression【关于数组中的插入 + 绝对值的性质 + 贪心一头一尾最值】
Pointer - character pointer
devkit入门
Meta AI西雅图研究负责人Luke Zettlemoyer | 万亿参数后,大模型会持续增长吗?
RAID disk redundancy queue
几百行代码实现一个 JSON 解析器
Anconda download + add Tsinghua +tensorflow installation +no module named 'tensorflow' +kernelrestart: restart failed, kernel restart failed
Spark SQL UDF function
云导DNS和知识科普以及课堂笔记
Curlpost PHP
[groovy] JSON serialization (convert class objects to JSON strings | convert using jsonbuilder | convert using jsonoutput | format JSON strings for output)
Study diary: February 13, 2022