当前位置:网站首页>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;
}
};
边栏推荐
- 时间戳的拓展及应用实例
- synchronized 和 ReentrantLock
- Extension and application of timestamp
- logstash清除sincedb_path上传记录,重传日志数据
- CTF daily question day44 rot
- Ffmpeg captures RTSP images for image analysis
- Spark AQE
- Idea远程提交spark任务到yarn集群
- Questions about database: (5) query the barcode, location and reader number of each book in the inventory table
- Anconda download + add Tsinghua +tensorflow installation +no module named 'tensorflow' +kernelrestart: restart failed, kernel restart failed
猜你喜欢

从 1.5 开始搭建一个微服务框架——调用链追踪 traceId
![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]

Anconda download + add Tsinghua +tensorflow installation +no module named 'tensorflow' +kernelrestart: restart failed, kernel restart failed

KDD 2022 | EEG AI helps diagnose epilepsy

Recoverable fuse characteristic test

MDK debug时设置数据实时更新

notepad++正則錶達式替換字符串

激动人心,2022开放原子全球开源峰会报名火热开启

可恢复保险丝特性测试

Installation and use of esxi
随机推荐
【EI会议分享】2022年第三届智能制造与自动化前沿国际会议(CFIMA 2022)
云导DNS和知识科普以及课堂笔记
Folding and sinking sand -- weekly record of ETF
看抖音直播Beyond演唱会有感
Location based mobile terminal network video exploration app system documents + foreign language translation and original text + guidance records (8 weeks) + PPT + review + project source code
I'm interested in watching Tiktok live beyond concert
vSphere实现虚拟机迁移
OpenCV经典100题
The third season of ape table school is about to launch, opening a new vision for developers under the wave of going to sea
MCU realizes OTA online upgrade process through UART
MIT博士论文 | 使用神经符号学习的鲁棒可靠智能系统
Cf:c. the third problem
Room cannot create an SQLite connection to verify the queries
Promise
Recoverable fuse characteristic test
MIT doctoral thesis | robust and reliable intelligent system using neural symbol learning
Cloud guide DNS, knowledge popularization and classroom notes
KDD 2022 | 脑电AI助力癫痫疾病诊断
China Taiwan strategy - Chapter 8: digital marketing assisted by China Taiwan
How to make your own robot