509. Fibonacci Number
The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,
F(0) = 0, F(1) = 1
F(n) = F(n - 1) + F(n - 2), for n > 1.
Given n, calculate F(n).
题目解析:
- 存储中间值,避免重复计算
- 使用滚动数组,节省空间
代码:
class Solution {
public int fib(int n) {
int[] arr = new int[3];
arr[0] = 0;
arr[1] = 1;
for (int i = 2; i <= n; i++) {
arr[i % 3] = arr[(i-1) % 3] + arr[(i-2) % 3];
}
return arr[n % 3];
}
}
70. Climbing Stairs
You are climbing a staircase. It takes n steps to reach the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
题目解析:
- 动态规划
代码:
class Solution {
public int climbStairs(int n) {
// dp[i]: represent distinct ways to reach i
int[] dp = new int[n+1];
dp[0] = 1;
for (int i = 1; i < n+1; i++) {
if (i - 1 >= 0) dp[i] += dp[i-1];
if (i - 2 >= 0) dp[i] += dp[i-2];
}
return dp[n];
}
}
746. Min Cost Climbing Stairs
You are given an integer array cost where cost[i] is the cost of ith step on a staircase. Once you pay the cost, you can either climb one or two steps.
You can either start from the step with index 0, or the step with index 1.
Return the minimum cost to reach the top of the floor.
题目解析:
- 注意目标值下标是cost.lenght 而不是 cost.length - 1
代码:
class Solution {
public int minCostClimbingStairs(int[] cost) {
int[] dp = new int[cost.length+1];
dp[0] = cost[0];
dp[1] = cost[1];
for (int i = 2; i <= cost.length; i++) {
dp[i] = Math.min(dp[i-1], dp[i-2]);
if (i != cost.length) dp[i] += cost[i];
}
return dp[cost.length];
}
}