1. 程式人生 > >【動態規劃】數塔問題

【動態規劃】數塔問題

//動態規劃數塔問題
#include<iostream>
using namespace std;
const int n = 5;
int d[n][n] = { {8},
				{12,15},
				{3,9,6},
				{8,10,5,12},
				{16,4,18,10,9} };
int DataTower(int d[n][n]) {
	int maxAdd[n][n] = { 0 };
	int path[n][n] = { 0 };
	int i, j;
	for (j = 0; j < n; j++) {
		maxAdd[n - 2][j] =
d[n - 2][j]; } for (i = n - 2; i >= 0; i--) { for (j = 0; j <= i; j++) { if (maxAdd[i + 1][j] > maxAdd[i + 1][j + 1]) { maxAdd[i][j] = d[i][j] + maxAdd[i + 1][j]; path[i][j] = j; } else { maxAdd[i][j] = d[i][j] + maxAdd[i + 1][j+1]; path[i][j] = j+1; } } }
cout << "The path is : " <<d[0][0]; j = path[0][0]; for (int i = 1; i < n; i++) { cout << " ---> " << d[i][j]; j = path[i][j]; } return maxAdd[0][0]; } int main() { cout << "maxAdd = " << DataTower(d)<<endl; //system("pause"); return 0; }