Digital Triangle
Narrative Description:
There is a non-negative integer triangle with only one number in the first row and one number in the lower left and bottom right.
Problem:
Start with the number of the first line. Each time you can go down one cell to the lower left or right. Until you reach the most downward, add up all the numbers that pass along the way.
How to walk the talent make this and as big as possible?
Analysis:
It is not difficult to see that this question is a dynamic decision-making problem: There are two choices at a time-bottom left or bottom right.
If we use backtracking to find out all possible routes, we can choose the best route from them. But as always, backtracking is inefficient: an n-level digital triangle has a 2^n line in its entirety. The speed of backtracking when n is very large is intolerable. Therefore, the discussion is implemented by recursive, recursive, and memory search methods, although there are other methods, but at this point we only discuss the comparison of the methods of learning more similar.
The first thing to think of is a recursive implementation:
#include "stdio.h" #define MAXN 100int a[maxn][maxn],n;inline max (int x,int y) {return x>y?x:y;} Recursive computations implement int d (int x,int y) {return a[x][y]+ (x==n?).0:max (d (X+1,y), D (x+1,y+1)));} int main () {while (~SCANF ("%d", &n)) {int i,j;for (i=1;i<=n;i++) {for (j=1;j<=i;j++) scanf ("%d", &a[i][j]);} printf ("max:%d\n", D ());} return 0;}
While this is true, time is inefficient. The reason for this is repeated calculations.
Example: D (3,2) is called repeatedly in the following calculations
D (2,1) calculation calls--D (3,1), D (3,2)
D (2,2) calculation calls--D (3,2), D (3,3)
Implementation of recursion:
#include "stdio.h" #define MAXN 100int a[maxn][maxn],n;inline max (int x,int y) {return x>y?X:y;} recursive implementation of int d (int x,int y) {int d[n][n],i,j; for (j=1;j<=n;j++) d[n][j]=a[n][j];for (i=n-1;i>=1;i--) {for (j=1;j<= i;j++) D[i][j]=a[i][j]+max (d[i+1][j],d[i+1][j+1]);} return d[x][y];} int main () {while (~SCANF ("%d", &n)) {int i,j;for (i=1;i<=n;i++) {for (j=1;j<=i;j++) scanf ("%d", &a[i][j]);} printf ("max:%d\n", D ());} return 0;}
Memory Search Implementation:
#include "stdio.h" #include "string.h" #define MAXN 100int a[maxn][maxn],n;int d[maxn][maxn];//Memory Search using the state memory array inline Max (int x,int y) {return x>y?x:y;} /* Memory word Search. The program is divided into two parts. First of all
Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.
Digital triangle-recursive, recursive, in-memory search