2013-03-01 62 views
0

我在网站上遇到问题。鉴于stringsst,我必须在s找到st的所有可能的组合。例如,为什么我在这里得到一个与内存相关的错误?

s  = "doomdogged" 
st  = "dg" 
answer = 4 

我可以选择从0或4的d和g从6或7.这给了我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; 
} 

首先我找字符st,并根据需要在我的布尔阵列目标发现它们标记。

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

最后,我计算那些有意义的,并输出答案。出于某种原因,我的代码不起作用,并在我标记的行上生成有关内存的运行时错误。

+1

''doomdogged''末尾的'd'怎么办? – Mankarse 2013-03-01 03:53:44

+0

我猜这个问题真的想要计算子序列,而不是组合。 – aschepler 2013-03-01 03:59:40

+0

是的组合。 “doomdogged”结尾的d不起作用,因为之后不会有任何先前的gs。 – 2013-03-01 04:13:45

回答

0

DFS_Enumeration可能会增加index任意次数,所以st[index]可能会超过字符串st的末尾。

+0

我一步一步地调试,然后在特定行发现错误。我的调试器显示memory.h中的错误。 – 2013-03-01 04:12:55

相关问题