poj1163 遞歸或dp

遞歸的版本:很可惜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<=i
	static 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了吧。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章