我在網站上遇到問題。鑑於string
s
和st
,我必須在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。
最後,我計算那些有意義的,並輸出答案。出於某種原因,我的代碼不起作用,並在我標記的行上生成有關內存的運行時錯誤。
''doomdogged''末尾的'd'怎麼辦? – Mankarse 2013-03-01 03:53:44
我猜這個問題真的想要計算子序列,而不是組合。 – aschepler 2013-03-01 03:59:40
是的組合。 「doomdogged」結尾的d不起作用,因爲之後不會有任何先前的gs。 – 2013-03-01 04:13:45