C++ 为什么我在这里遇到与内存相关的错误?

C++ 为什么我在这里遇到与内存相关的错误?,c++,memory,memory-management,vector,C++,Memory,Memory Management,Vector,我在一个网站上遇到了一个问题。给定字符串s和st,我必须在s中找到st的所有可能组合。比如说, s = "doomdogged" st = "dg" answer = 4 我可以从0或4中选择d,从6或7中选择g。这给了我4种可能的组合 这是我的密码: #include <iostream> #include <vector> using namespace std; string s, st; bool target[26]; vector&l

我在一个网站上遇到了一个问题。给定
字符串
s
st
,我必须在
s
中找到
st
的所有可能组合。比如说,

s      = "doomdogged"
st     = "dg"
answer = 4
我可以从0或4中选择d,从6或7中选择g。这给了我4种可能的组合

这是我的密码:

#include <iostream>
#include <vector>

using namespace std;

string s, st;

bool target[26];
vector<int> positions[26];
vector<vector<int>> possibleCombinations;

void DFS_Enumeration(int, vector<int>*);
int DFS_index_max = 0;

int main(int argc, char *argv[])
{
    int    answer = 0;
    cin >> s;  //Given a string s
    cin >> st; //Given a string st
    //Find all possible combination of st in s
    for ( int i = 0 ; i < 26 ; ++ i )
        target[i] = 0;
    for ( int i = 0 ; i < st.length() ; ++ i )
        target[st[i] - 97] = 1;
    for ( int i = 0 ; i < 26 ; ++ i )
    {
        if ( target[i] == 0 ) continue;
        for ( int j = 0 ; j < s.length() ; ++ j )
        {
            if ( s[j] == i + 97 ) positions[i].push_back(j);
        }
    }
    DFS_index_max = st.length();
    vector<int> trail(0);
    DFS_Enumeration(0, &trail); //Here I got an runtime error
    for ( vector<int> vi : possibleCombinations )
    {
        int currentMax = 0;
        for ( int i = 0 ; i < vi.size() ; ++ i )
        {
            if ( vi[i] > currentMax )
            {
                if ( i == vi.size() - 1 ) ++ answer;
                currentMax = vi[i];
                continue;
            }
            else
                break;
        }
    }
    cout << answer;
}

void DFS_Enumeration(int index, vector<int>* trail)
{
    if ( index == DFS_index_max )
    {
        possibleCombinations.push_back(*trail);
        return;
    }
    for ( int i = 0 ; i < positions[st[index] - 97].size() ; ++ i )
    {
        trail -> push_back(positions[st[index] - 97][i]);
        DFS_Enumeration(++index, trail);
        trail -> pop_back();
    }
    return;
}
#包括
#包括
使用名称空间std;
字符串s,st;
布尔目标[26];
向量位置[26];
向量可能组合;
void DFS_枚举(int,vector*);
int DFS_index_max=0;
int main(int argc,char*argv[])
{
int-answer=0;
cin>>s;//给定一个字符串s
cin>>st;//给定一个字符串st
//在s中找到所有可能的st组合
对于(int i=0;i<26;++i)
目标[i]=0;
对于(int i=0;icurrentMax)
{
如果(i==vi.size()-1)+回答;
currentMax=vi[i];
继续;
}
其他的
打破
}
}
不能向后推(位置[st[指数]-97][i];
DFS_枚举(++索引,跟踪);
trail->pop_back();
}
返回;
}
首先,我在
st
中查找字符,并根据需要在布尔数组目标中标记它们

然后,我使用DFS枚举所有可能的组合。对于上面的“doomdogged”和“dg”示例,d存在于0、4、9中。g存在于6,7。我会得到06,07,46,47,96,97


最后,我计算那些有意义的,并输出答案。由于某些原因,我的代码无法工作,并且在我标记的行中生成了一个有关内存的运行时错误。

DFS\u枚举
可能会增加
index
任意次数,因此
st[index]
可能会超过字符串的末尾
st

那么
d
末尾的
呢“doomdogged”
?我猜问题真的是要计算子序列,而不是组合。是的组合。“doomdogged”结尾的d不起作用,因为后面不会有任何前面的G。我一步一步地调试,在那一行我得到了错误。我的调试器在memory.h处向我显示了错误。