dp 數字三角形
阿新 • • 發佈:2020-07-23
凍龜之前
先看地龜
1 // 2 // Created by snnnow on 2020/7/23 3 // 4 //遞迴演算法,除了慢其實還好 5 #include<iostream> 6 #include<stdio.h> 7 #include<stdlib.h> 8 #include<time.h> 9 #include <queue> 10 using namespace std; 11 #define Max 101 12 int m[Max][Max]; 13 int n; 14 int dfs(int a,int b){15 if(a==n) 16 return m[a][b]; 17 return max(dfs(a+1,b),dfs(a+1,b+1))+m[a][b]; 18 } 19 int main(){ 20 21 scanf("%d",&n); 22 for (int i = 1; i <= n; ++i) { 23 for (int j = 1; j <= i ; ++j) { 24 scanf("%d",&m[i][j]); 25 26 } 27 28 }29 printf("%d",dfs(1,1)); 30 }
加個記憶化搜素
1 // 2 // Created by snnnow on 2020/7/23 3 // 4 //遞迴演算法,除了慢其實還好 5 #include<iostream> 6 #include<stdio.h> 7 #include<stdlib.h> 8 #include<time.h> 9 #include <queue> 10 #include <time.h> 11 using namespace std; 12 #define Max 101 13int m[Max][Max]; 14 int rem[Max][Max]; 15 int n; 16 int dfs(int a,int b){ 17 if(rem[a][b]!=-1) 18 return rem[a][b]; 19 if(a==n) 20 rem[a][b]= m[a][b]; 21 else 22 rem[a][b]=max(dfs(a+1,b),dfs(a+1,b+1))+m[a][b]; 23 24 return rem[a][b]; 25 } 26 int main(){ 27 28 scanf("%d",&n); 29 for (int i = 1; i <= n; ++i) { 30 for (int j = 1; j <= i ; ++j) { 31 scanf("%d",&m[i][j]); 32 rem[i][j]=-1; 33 34 } 35 36 } 37 printf("%d",dfs(1,1)); 38 cout<<endl; 39 printf("Time used = %.2f\n", (double)clock() / CLOCKS_PER_SEC); 40 41 }