1. 程式人生 > >動態規劃(DP)

動態規劃(DP)

first 個數 目的 進入 right 返回值 ase lines cal

在學習動態規劃前 , 先補充些有關遞歸的知識 。

  

  所謂的遞歸函數 就是調用自身函數的過程 ,因此是用棧來存儲的

  遞歸函數的最終返回值 就是第一次調用函數的返回值 。

  在寫函數遞歸時 , 要特別註意的兩點 :

    一是 遞歸 遞歸 , 一定有讓它有能讓他回歸的條件 。

    二是 寫遞歸時 , 要找到一個最簡單的關系式 , 方便寫遞歸函數 。

話不多說 , 進入正題 , 先看這道題 。( poj 1163 )

7
3 8
8 1 0
2 7 4 4
4 5 2 6 5

(Figure 1)
Figure 1 shows a number triangle. Write a program that calculates the highest sum of numbers passed on a route that starts at the top and ends somewhere on the base. Each step can go either diagonally down to the left or diagonally down to the right.

Input

Your program is to read from standard input. The first line contains one integer N: the number of rows in the triangle. The following N lines describe the data of the triangle. The number of rows in the triangle is > 1 but <= 100. The numbers in the triangle, all integers, are between 0 and 99.

Output

Your program is to write to standard output. The highest sum is written as an integer.

Sample Input

5
7
3 8
8 1 0 
2 7 4 4
4 5 2 6 5

Sample Output

30


題目的意思是 : 從上到下 ,每次可以走左下角 或者右下角 , 問最大和是多少 。

  我們可以用一個二維數組去存放此三角形 。
   用 pre[i][j] 表示 第 i 行 第 j 個數 ,每次移動可以有兩種選擇 , 選擇向左下走 , 即 pre[i+1][j] , 或者選擇向 右下走 , 即 pre[i+1][j+1] , 若走到最後一行時 ,則返回 pre[i][j] , 不在調用 。



動態規劃(DP)