两题都能用dp做,首次2AC,纪念一下
第一题
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
if(n==1){
System.out.println(2);
return;
}
if(n==2){
System.out.println(3);
return;
}
if(n==3){
System.out.println(5);
return;
}
String[] a=new String [n+1];
a[1]=new String("2");
a[2]=new String("3");
a[3]=new String("5");
for(int i=4;i<a.length;i++){
int p=i%3;
int k=i/3;
if(p!=0){
a[i]=a[k]+a[p];
}else {
a[i]=a[k-1]+a[3];
}
}
System.out.println(Integer.parseInt(a[n].toString()));
}
}
第二题
package com.company;
import java.util.Arrays;
import java.util.Scanner;
public class Main2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = Integer.parseInt(scanner.nextLine());
int[][] dp = new int[n][];
for(int i=0;i<n;i++){
String[] split = scanner.nextLine().trim().split(" ");
dp[i]=new int[2*i+1];
for(int j=0;j<dp[i].length;j++){
dp[i][j]=Integer.parseInt(split[j]);
}
}
for(int i=n-2;i>=0;i--){
for(int j=0;j<2*i+1;j++){
dp[i][j]=dp[i][j]+Math.max(dp[i+1][j],Math.max(dp[i+1][j+1],dp[i+1][j+2]));
}
}
System.out.println(dp[0][0]);
}
}
全部评论
(3) 回帖