import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in=new Scanner(System.in); while(in.hasNext()) { //数据层数 int n=in.nextInt(); int a[][]=new int[n][n]; for(int i=0;i<n;i++){ for(int j=0;j<=i;j++){ a[i][j]=in.nextInt(); } } //从第一层开始递归即a【0】【0】 System.out.println(solve(n,a,0,0)); } } private static int solve(int n,int[][] a,int i,int j) { // TODO Auto-generated method stub //超出a的范围,结束递归 if(i==n){return 0;} //选择下一层直下面的路径小还是右下的路径小 else{return b[i][j]=a[i][j]+Math.max(solve(n,a,b,i+1,j),solve(n,a,b,i+1,j+1)); } } } 改成C++语言。
时间: 2024-04-14 22:30:40 浏览: 97
Sure! Here's the equivalent code in C++:
```cpp
#include <iostream>
#include <vector>
using namespace std;
int solve(int n, vector<vector<int>>& a, int i, int j) {
if (i == n) {
return 0;
}
else {
return a[i][j] + max(solve(n, a, i+1, j), solve(n, a, i+1, j+1));
}
}
int main() {
int n;
while (cin >> n) {
vector<vector<int>> a(n, vector<int>(n));
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
cin >> a[i][j];
}
}
cout << solve(n, a, 0, 0) << endl;
}
return 0;
}
```
Please note that the code assumes the input values are provided correctly and doesn't include error handling.
阅读全文