dfs解决数塔问题;

dfs解决数塔问题;

#include <iostream>

#include <stdio.h>
#include <vector> 
using namespace std;
const int maxn=200;
int tower[maxn][maxn];
vector<int> temp,ans;
int n;
int maxsum=-1;
void dfs(int x,int y,int count){
if(x==n){
if(count>maxsum){
maxsum=count;
ans=temp; 
return ;
}
}
if(x==1 && y==1){
temp.push_back(tower[x][y]);
}
if(x+1<=n && y<=x+1){
temp.push_back(tower[x+1][y]);
dfs(x+1,y,count+tower[x+1][y]);
temp.pop_back();
}
if(x+1<=n && y+1<=x+1){
temp.push_back(tower[x+1][y+1]);
dfs(x+1,y+1,count+tower[x+1][y+1]);
temp.pop_back();
}
}             
int main(int argc, char** argv) {
scanf("%d",&n);
for(int i=1;i<=n;i++){
for(int j=1;j<=i;j++){
scanf("%d",&tower[i][j]);
}
}
dfs(1,1,tower[1][1]);
printf("最优路径:\n");
for(vector<int>::iterator it=ans.begin();it!=ans.end();it++){
printf("%d ",*it);
}
putchar('\n');
printf("%d",maxsum);
return 0;
}