题解 | #最小花费爬楼梯#
最小花费爬楼梯
https://www.nowcoder.com/practice/9b969a3ec20149e3b870b256ad40844e
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = Integer.valueOf(in.nextLine()); int[] cost = new int[n]; // for循环将cost数组初始化,注意全部数据在第二行输入,所以用nextInt() // 注意 hasNext 和 hasNextLine 的区别 for(int i = 0; i < n; i++){ cost[i] = in.nextInt(); } int[] dp = new int[n]; if(n == 0){ System.out.println(0); } if(n == 1){ System.out.println(cost[0]); } // dp数组初始化,是根据递推公式推导的,因为输出选出两者最小 dp[0] = cost[0]; dp[1] = cost[1]; for(int i = 2; i < n; i++){ // 递推公式,为什么不是加cost[i-1],cost[i-2],因为当你选择跳上这个台阶时, // 然要花费此台阶的cost,要考虑进去 dp[i] = Math.min(dp[i-1] ,dp[i-2]) + cost[i]; } System.out.println(Math.min(dp[n-2],dp[n-1])); } }