poj1163 遞迴或dp

來源:互聯網
上載者:User

遞迴的版本:很可惜tle了。

package p1163;import java.io.File;import java.io.FileNotFoundException;import java.util.Scanner;public class Main {static int count = 105;static int d[][] = new int[count][count];static int n;public static void main(String[] args) throws FileNotFoundException {//File f = new File("c:\\data.txt");//Scanner cin = new Scanner(f); Scanner cin = new Scanner(System.in);n = cin.nextInt();for (int i = 1; i <= n; i++) {for (int j = 1; j <= i; j++) {d[i][j] = cin.nextInt();}}System.out.println(func(1, 1));}// i行,j列,j<=istatic int func(int i, int j) {int max = 0;if (i < n) {max = d[i][j] + max(func(i + 1, j), func(i + 1, j + 1));// 往下,往右} else {max = d[i][j];}return max;}static int max(int a, int b) {return a > b ? a : b;}}

想了一下,tle的原因主要是遞迴是從上往下計算的。那麼用動規呢,從下往上計算。

--------------------------------------------------------------------------粉葛--------------------------------------------------------------------------

動規的版本:

import java.io.File;import java.io.FileNotFoundException;import java.util.Scanner;public class Main {static int count = 105;static int d[][] = new int[count][count];static int res[][] = new int[count][count];//使用res儲存已經計算出來的資料static int n;public static void main(String[] args) throws FileNotFoundException {//File f = new File("c:\\data.txt");//Scanner cin = new Scanner(f); Scanner cin = new Scanner(System.in);n = cin.nextInt();for (int i = 1; i <= n; i++) {for (int j = 1; j <= i; j++) {d[i][j] = cin.nextInt();}}for (int i = 1; i <= n; i++) {res[n][i] = d[n][i];}// 從下往上動規for (int i = n; i >= 1; i--) {for (int j = 0; j <= i; j++) {res[i][j] = d[i][j] + max(res[i + 1][j], res[i + 1][j + 1]);}}System.out.println(res[1][1]);//最後,res數組的頂層的那個元素就是要求的最大值}static int max(int a, int b) {return a > b ? a : b;}}

其實動規跟上面的遞迴版本,差不是很多。都是從底層計算,然後向上層累加。只是遞迴版本的應該是需要遞迴很多次,所以算上遞迴返回的時間,就tle了吧。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.