DP 入门 洛谷P1216 数字三角形
数字三角形
1. DP 从下往上推
import java.util.Scanner;
public class P1216 {
public static void main(String[] args) {
Scanner kb=new Scanner(System.in);
int n=kb.nextInt();
int dp[][]=new int[n][n];
for (int i = 0;i<n; i++) {
for (int j = 0; j <=i; j++) {
dp[i][j]=kb.nextInt();
}
}
for (int i = n-2;i>=0; i--) {
for (int j = 0; j <=i; j++) {
dp[i][j]+=Math.max(dp[i+1][j], dp[i+1][j+1]);
}
}
System.out.println(dp[0][0]);
}
}
2 从上往下推 找出最后一行最大值
import java.util.Scanner;
public class P1216 {
public static void main(String[] args) {
Scanner kb=new Scanner(System.in);
int n=kb.nextInt();
int dp[][]=new int[n+1][n+1];
for (int i = 1;i<=n; i++) {
for (int j = 1; j <=i; j++) {
dp[i][j]=kb.nextInt();
}
}
int ans=0;
for (int i = 1;i<=n; i++) {
for (int j = 1; j <=i; j++) {
dp[i][j]+=Math.max(dp[i-1][j], dp[i-1][j-1]);
ans=Math.max(ans, dp[i][j]);
}
}
System.out.println(ans);
}
}
3记忆化搜索
搜索 55分 超时了
import java.util.Scanner;
public class P1216 {
static int f[][];
static int a[][];
static int n=0;
public static void main(String[] args) {
Scanner kb=new Scanner(System.in);
n=kb.nextInt();
f=new int [n+1][n+1];
a=new int[n+1][n+1];
for (int i = 1;i<=n; i++) {
for (int j = 1; j <=i; j++) {
a[i][j]=kb.nextInt();
//f[i][j]=-1;
}
}
System.out.println(dfs(1, 1));
}
static int count=0;
static int ans=0;
private static int dfs(int x, int y) {
// TODO Auto-generated method stub
count+=a[x][y];
if (x==n) {//到最后一层了 出口
ans=Math.max(ans, count);
}else {
dfs(x+1, y);
dfs(x+1, y+1);
}
count-=a[x][y];//回溯辉去 减去走过的值
return ans;
}
}
改成记忆化 100%
import java.util.Scanner;
public class P1216 {
static int f[][];
static int a[][];
static int n=0;
public static void main(String[] args) {
Scanner kb=new Scanner(System.in);
n=kb.nextInt();
f=new int [n+1][n+1];
a=new int[n+1][n+1];
for (int i = 1;i<=n; i++) {
for (int j = 1; j <=i; j++) {
a[i][j]=kb.nextInt();
f[i][j]=-1;
}
}
System.out.println(dfs(1, 1));
}
private static int dfs(int x, int y) {
int ans=0;
// TODO Auto-generated method stub
if (x==n) {//到最后一层了 出口
return a[x][y];
}
if (f[x+1][y]==-1) {
f[x+1][y]=dfs(x+1, y);
}
if (f[x+1][y+1]==-1) {
f[x+1][y+1]=dfs(x+1, y+1);
}
ans=Math.max(f[x+1][y], f[x+1][y+1])+a[x][y];
return ans;
}
}