将这篇代码由Python转为C++:def findPaths(m: int, n: int) -> List[str]: # 计算不同走法数目 dp = [[0] * (n + 1) for _ in range(m + 1)] dp[1][1] = 1 for i in range(1, m + 1): for j in range(1, n + 1): if i == 1 or j == 1: dp[i][j] = 1 else: dp[i][j] = dp[i - 1][j] + dp[i][j - 1] # 递推出具体路径 paths = [] def dfs(i, j, path): if i == 1 and j == 1: paths.append(path[::-1]) return if i > 1 and dp[i - 1][j] > 0: dfs(i - 1, j, path + 'D') if j > 1 and dp[i][j - 1] > 0: dfs(i, j - 1, path + 'R') dfs(m, n, '') # 按字典序升序排序 paths.sort() return paths
时间: 2024-01-21 16:04:53 浏览: 60
以下是将 Python 代码转换为 C++ 代码的实现:
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<string> findPaths(int m, int n) {
// 计算不同走法数目
vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));
dp[1][1] = 1;
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (i == 1 || j == 1) {
dp[i][j] = 1;
} else {
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
}
}
// 递推出具体路径
vector<string> paths;
function<void(int, int, string)> dfs = [&](int i, int j, string path) {
if (i == 1 && j == 1) {
paths.push_back(string(path.rbegin(), path.rend()));
return;
}
if (i > 1 && dp[i - 1][j] > 0) {
dfs(i - 1, j, path + 'D');
}
if (j > 1 && dp[i][j - 1] > 0) {
dfs(i, j - 1, path + 'R');
}
};
dfs(m, n, "");
// 按字典序升序排序
sort(paths.begin(), paths.end());
return paths;
}
int main() {
int m = 2, n = 3;
vector<string> paths = findPaths(m, n);
for (const string& path : paths) {
cout << path << endl;
}
return 0;
}
```
注意,由于 C++ 不支持直接使用 lambda 函数,因此需要使用 `std::function` 类型来定义递归函数。在递推出具体路径时,需要使用 `std::string` 类型的反转迭代器 `rbegin()` 和 `rend()` 来实现字符串反转。
阅读全文