你需要爬上一个 n 层的楼梯,在爬楼梯过程中, 每阶楼梯需花费非负代价,第i阶楼梯花费代价表示为 cost[i] , 一旦你付出了代价,你可以在该阶基础上往上爬一阶或两阶。
你可以从第 0 阶或者 第 1 阶开始,请找到到达顶层的最小的代价是多少。
n 和 cost[i] 皆为整数
数据范围:
, 
输入为一串半角逗号分割的整数,对应cost数组,例如
10,15,20
输出一个整数,表示花费的最小代价
1,100,1,1,1,100,1,1,100,1
6
import java.util.Scanner;
import java.util.Arrays;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextLine()) { // 注意 while 处理多个 case
// 输入的处理,真是麻烦,还好有流处理
String nStr = in.nextLine();
int[] cost = Arrays.stream(nStr.split(",")).mapToInt(Integer::parseInt).toArray();
int n = cost.length;
// f(i): 到第 i 层的最小代价
// f(i) = min{f(i - 1) + cost[i - 1], f(i - 2) + cost[i - 2]}
// f(0) = 0, f(1) = 0
int[] dp = new int[2];
for (int i = 2; i <= n; i++) {
dp[i % 2] = Math.min(dp[(i - 1) % 2] + cost[i - 1], dp[(i - 2) % 2] + cost[i - 2]);
}
System.out.println(dp[n % 2]);
}
}
} /*
*/
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
String str = input.next();
//字符串将‘,’取出后的字符数组
String[] arr = str.split(",");
int[] cost = new int[arr.length];
//字符数组转为int数组
for(int i = 0;i<arr.length;i++){
cost[i] = Integer.parseInt(arr[i]);
}
//判断是从第一阶还是第0阶开始
int step = 0;
int sum = cost[0];
if(cost[0]>=cost[1]){
step = 1;
sum = cost[1];
}
while(step<cost.length-2){
int test1 = cost[step] + cost[step+1];
int test2 = cost[step] + cost[step+2];
if(test1>=test2){
sum+=cost[step+2];
step+=2;
}else{
sum+=cost[step+1];
step++;
}
}
System.out.println(sum);
}
} 有没有大神能帮我看看,我这种方法怎么会不能完全通过呢?import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String s = sc.nextLine();
String[] split = s.split(",");
int[] a = new int[split.length];
for (int i = 0; i < split.length; i++)
a[i] = Integer.parseInt(split[i]);
int[] dp = new int[a.length + 1];
dp[0] = 0;
dp[1] = 0;
for (int i = 2; i < dp.length; i++) {
dp[i] = Math.min(dp[i - 1] + a[i - 1], dp[i - 2] + a[i - 2]);
}
System.out.println(dp[dp.length-1]);
}
}
}