c++ - 对于具有重复字符的字符串,字符串的排列失败
问题描述
我试图了解回溯是如何工作的。我正在研究字符串的排列。
class Solution {
public:
void permute(string s,int count[], string res, int level, vector<string> &perS)
{
if( level == s.size())
{
//cout<<res<<endl;
perS.push_back(res);
return;
}
int i;
for(i=0; i<s.size(); i++)
{
if(count[i]==0)
{
continue;
}
res += s[i];
count[i]--;
permute(s, count, res, level+1, perS);
count[i]++;
//this line is problem I think?? how to handle if s1 contains duplicates??
res.erase(res.end()-1);
}
}
bool checkInclusion(string s1, string s2) {
map<char, int> mp;
for(int i=0; i<s1.size(); i++)
{
mp[s1[i]]++;
}
int *count = new int[mp.size()];
set<char> us;
//to generate the count array of all the characters
for(int i=0; i<s1.size(); i++)
{
us.insert(s1[i]);
}
auto it = us.begin();
for(int i=0; i<mp.size(); i++)
{
count[i] = mp[*it++]++;
}
string res;
vector<string> perS;
permute(s1, count, res, 0, perS);
//check if s2 contains in pers;
for(string x:perS)
{
if(s2.find(x)!=string::npos)
return true;
}
return false;
}
};
上面的代码在我将 s1 作为“helo”传递时有效,但如果它有重复项,则会给出 stackoverflow 错误。“你好”。
我试图理解的算法非常简单。我们从字符串中选择一个字符并遍历其他字符。一旦我们到达终点,我们就会回溯并检查其他选项。
我试过但无法理解为什么它因字符串重复而失败。 https://www.youtube.com/watch?v=nYFd7VHKyWQ&t=1346s 我正在尝试上述网址中解释的相同算法,但我正在尝试用 cpp 语言对其进行编码。
我非常感谢您对此的任何意见。这是我的第一个问题,请原谅我的任何错误。它将帮助我可视化回溯问题的递归流程。
解决方案
推荐阅读
- android - 我应该怎么做才能修复android gradle错误?
- python-3.x - 如何使用 Django TestCase 模拟(PyActiveResource)pyactiveresource.connection UnauthorizedAccess 响应返回?
- java - java - 如何从java中的kafka消息中获取密钥?
- javascript - HTML表单获取按钮上的单选输入值单击Javascript
- docker - “/remote_debugger/vsdbg:未找到”和“无法启动调试适配器”与 docker-compose
- chart.js - Chart JS - 如何在切片上显示标签而不是悬停时的文本
- bash - 循环遍历表并将多个参数解析到 Bash 中的脚本
- google-cloud-platform - GCP Metrics Explorer - “指标数据”历史?
- php - 如何使用 php mail() 函数将多个图像从不同的输入字段发送到电子邮件
- python - 如果存在于字典列表中,则检查和附加列表中的项目的最佳代码