POJ-1163-The Triangle: DP入门 递归 递推
递归思路 超时算法
#include<iostream> using namespace std; #define Size 101 int Triangle[Size][Size]; int n; int GetAns( int i, int j ) { if( i==n ) return Triangle[i][j]; int x=GetAns( i+1, j ); int y=GetAns( i+1, j+1 ); return max(x, y)+Triangle[i][j]; } int main() { cin>>n; for( int i=1; i<=n; i++ ) for( int j=1; j<=i; j++ ) cin>>Triangle[i][j]; cout<<GetAns(1, 1)<<endl; return 0; }
上述算法优化: 记忆型递归
#include<iostream> using namespace std; #define Size 101 int Triangle[Size][Size]; int Table[Size][Size]; int n; int GetAns( int i, int j ) { if( Table[i][j]!=-1 ) return Table[i][j]; if( i==n ) Table[i][j] = Triangle[i][j]; else{ int x=GetAns( i+1, j ); int y=GetAns( i+1, j+1 ); Table[i][j] = max(x, y)+Triangle[i][j]; } return Table[i][j]; } int main() { cin>>n; for( int i=1; i<=n; i++ ) for( int j=1; j<=i; j++ ){ cin>>Triangle[i][j]; Table[i][j]=-1; } cout<<GetAns(1, 1)<<endl; return 0; }
/*通过引入记忆表 Table 当每算出一个Table(i,j)就保存起来,下次用到其值的时候直接取用,则可免去重复计算。*/
上述递归算法 转 递推(“人人为我”型)
#include<iostream> using namespace std; #define Size 101 int Triangle[Size][Size]; int Table[Size][Size]; int n; int main() { cin>>n; for( int i=1; i<=n; i++ ) for( int j=1; j<=i; j++ ) cin>>Triangle[i][j]; for( int i=1; i<=n; i++ ) Table[n][i] = Triangle[n][i]; for( int i=n-1; i>=1; i-- ) for( int j=1; j<=i; j++ ) Table[i][j] = max(Table[i+1][j] , Table[i+1][j+1]) + Triangle[i][j]; cout<<Table[1][1]<<endl; return 0; }