C++通过向量中的值来推回字符串



我正在处理一些算法问题,在C++中管理函数、向量和字符串时遇到了问题。

我必须在矩阵中找到一条具体的路径,为此,我需要所有不同的路径,所以我决定使用一个函数。此功能将检查继续搜索的位置。这是函数的代码:

vector<string> get_all_paths(string actual, int rows, int columns, int col_actual, int row_prev) {
vector<string> solutions;
int row_actual = (rows+row_prev-1)%rows;
for (int i = 0; i < 3; i++) {
cout << col_actual << " " << row_actual << "n";
//cout << (dp[row_prev][col_actual+1] - matrix[row_prev][col_actual+1]) << " " << dp[row_actual][col_actual] << "n";
if( (dp[row_prev][col_actual+1] - matrix[row_prev][col_actual+1]) == dp[row_actual][col_actual] ) {
if (col_actual > 0) {
//cout << "--" << actual << " " << row_actual << "n";
string branch = actual + to_string(row_actual+1) + " ";
solutions = get_best_path(branch, rows, columns, col_actual-1, row_actual);
//cout << ".." << actual << "n"; 
} else {
//cout << actual << " " << row_actual << "n";
cout << actual << "n";
string branch = actual.c_str();
branch += to_string(row_actual+1);
cout << branch << "n";
solutions.push_back( branch );
break;
}
}
row_actual = (row_actual+1)%rows;
}
for(auto i : solutions) cout << "--" << i << "n";
return solutions;
}

这是对方法的调用:

vector<string> solutions;
for (int i = 0; i < rows; i++) {
if (dp[i][cols-1] == min_path) {
cout << "................n";
solutions = get_best_path( (to_string(i+1)+" "), rows, cols, cols-2, i);
for(auto i : solutions) {
reverse(i.begin(), i.end());
cout << i << "n";
}
cout << "xxxxxxxxxxxxxxxn";
}
}

问题是,对于给定的例子,我得到了三个路径,这是正确的,但它们都是相同的字符串,这是变量分支中的最后一个路径或最后一次更改。

也许我混淆了很多概念,也许这个问题已经被回答了很多次,但我搜索过了,一无所获。

编辑:我没有从函数中得到三个路径,只有最后一个,但当在函数内部打印时,我在函数内部有三个路径都具有相同的值,很抱歉。

第二版:这个问题的思想是在给定的矩阵中找到最小代价路径,如果有超过1个,则在字典中找到最小的路径。给定一个矩阵:

5 4

9 1 9 9

1 9 9

9 9 9

1 1 1 1

9 9 1 9

我的方法是使用dp作为具有动态编程结果的矩阵,然后我尝试在上面的函数中重新创建所有路径。

在这种情况下,dp矩阵为:

9 2 11 12

1 10 11 20

9 10 11 12

1 2 3 4

9 10 3 12

因此,最好的途径是:

4 4 4 4

4 5 4 4

2 1 5 4

正确的是最后一个。

在我的函数中,我确实得到了不同的路径,并将它们添加到结果的向量中,但在搜索更多路径时会丢失它们。

如果你读过这篇文章,谢谢你抽出时间:D!

认为问题就在这里

solutions = get_best_path(branch, rows, columns, col_actual-1, row_actual);

因为该任务将取代您迄今为止可能找到的任何解决方案。相反,您应该将返回的任何解决方案附加到迄今为止找到的任何解决方法中。换句话说,类似的东西

vector<string> tmp = get_best_path(branch, rows, columns, col_actual-1, row_actual);
solutions.insert(solutions.end(), tmp.begin(), tmp.end());

但这只是直觉,我没有测试任何东西。

最新更新