數字三角形問題 演算法入門經典
阿新 • • 發佈:2019-02-07
遞迴方法:
記憶搜尋(遞迴):#include <stdio.h> #define maxn 100 int buf[maxn][maxn]; int n; int d(int i, int j){ int t1, t2; return i == n ? buf[i][j] : buf[i][j] + (((t1 = d(i+1, j)) > (t2 = d(i+1, j+1))) ? t1 : t2); } int main(){ /*5 9 12 15 10 6 8 2 18 9 5 19 7 10 4 16 結果 59*/ int i, j; scanf("%d", &n); for(i = 1; i <=n; ++i) for(j = 1; j <= i; ++j) scanf("%d", &buf[i][j]); printf("%d\n", d(1, 1)); return 0; }
#include <stdio.h> #include <string.h> #define maxn 100 int buf[maxn][maxn]; int d[maxn][maxn]; int n; int dfunc(int i, int j){ if(d[i][j] >= 0) return d[i][j]; return d[i][j] = buf[i][j] + (i == n ? 0 : dfunc(i+1, j) > dfunc(i+1, j+1) ? dfunc(i+1, j) : dfunc(i+1, j+1)); } int main(){ int i, j; scanf("%d", &n); for(i = 1; i <= n; ++i) for(j = 1; j <= i; ++j) scanf("%d", &buf[i][j]); memset(d, -1, sizeof(d)); printf("%d\n", dfunc(1, 1)); return 0; }
遞推方法:
#include <stdio.h> #define maxn 200 int d[maxn][maxn]; int n; void dfunc(){ int i, j; for(i = n - 1; i >= 1; --i) for(j = 1; j <= i; ++j) d[i][j] += d[i+1][j] > d[i+1][j+1] ? d[i+1][j]:d[i+1][j+1]; } int main(){ int i, j; scanf("%d", &n); for(i = 1; i <= n; ++i) for(j = 1; j <= i; ++j) scanf("%d", &d[i][j]); dfunc(); printf("%d\n", d[1][1]); return 0; }