8.27 京东笔试 2ac
1.使用队列
package jingdong_01;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Deque<Integer> q = new LinkedList<>();
q.addLast(2);
q.addLast(3);
q.addLast(5);
int k = 0;
while (!q.isEmpty()){
int temp = q.pollFirst();
k++;
if(k == n){
System.out.println(temp);
break;
}
q.addLast(temp * 10 + 2);
q.addLast(temp * 10 + 3);
q.addLast(temp * 10 + 5);
}
}
}
2.dp动态规划,处理输入时一开始用他提示的方式,咋都出错,最后还是用了nextInt(),ac;
package jingdong_02;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int a[][] = new int[n][2*n - 1];
for(int i = 0;i < n;i++){
for(int k = (2*n-1)/2 - i;k < (2*n - 1)-((2*n-1)/2 - i);k++){
a[i][k] = sc.nextInt();
}
}
for(int i = 1;i < n;i++){
for(int j = 0;j < a[0].length;j++){
if(j == 0){
a[i][j] = Math.max(a[i - 1][j],a[i - 1][j + 1]) + a[i][j];
}else if(j == a[0].length - 1){
a[i][j] = Math.max(a[i - 1][j],a[i - 1][j - 1]) + a[i][j];
}else{
int temp = Math.max(a[i - 1][j],a[i - 1][j - 1]);
a[i][j] = Math.max(temp,a[i - 1][j + 1]) + a[i][j];
}
}
}
int res = a[n - 1][0];
for(int k = 0;k < a[0].length;k++){
if (a[n - 1][k] > res){
res = a[n - 1][k];
}
}
System.out.println(res);
}
}
