509. 斐波那契数
public static int fib(int n) {// 找出最后一步// 定义损失函数 定义记忆化存储基本单元// 状态转移方程 f(n) = f(n-2)+f(n-1); n > 0// 边界 (递归过程中需要判断)// 初始化 (在未递归之前需要处理)// 返回答案if (n == 0) {return 0;}if (n == 1) {return 1;}int[] dp = new int[n];dp[0] = 0;dp[1] = 1;for (int i = 2; i < n; i++) {findFibonacci(i, dp);}return dp[n - 1] + dp[n - 2];}public static void findFibonacci(int n, int[] dp) {dp[n] = dp[n - 1] + dp[n - 2]; }
70. 爬楼梯
public static int climbStairs(int n) {//找出最后一步//定义损失函数 定义记忆化存储基本单元//状态转移方程 f(n) = f(n-2)+2; n > 0// f(n) = f(n-1)+1; n > 0//边界 (递归过程中需要判断)//初始化 (在未递归之前需要处理)//返回答案if (n == 0) {return 0;}if (n == 1) {return 1;}if (n == 2) {return 2;}int[] dp = new int[n];dp[0] = 0;dp[1] = 1;dp[2] = 2;for (int i = 3; i < n; i++) {climbStair(i, dp);}return dp[n - 1] + dp[n - 2]; }public static void climbStair(int n, int[] dp) {dp[n] = dp[n - 1] + dp[n - 2]; }
746. 使用最小花费爬楼梯
public static int minCostClimbingStairs(int[] cost) {int stairCase = cost.length + 1;// 找出最后一步// 定义损失函数 定义记忆化存储基本单元// 状态转移方程 f(n) = cost[n-1] > cost[n-2]?cost[n-2]:cost[n-1] n>2// f(n) = f(n-1)+1; n > 0// 边界 (递归过程中需要判断)// 初始化 (在未递归之前需要处理)// 返回答案if (stairCase == 1) {return 0;}if (stairCase == 2) {return cost[0];}int[] dp = new int[cost.length + 2];dp[0] = 0;dp[1] = 0;dp[2] = 0;for (int i = 3; i < dp.length; i++) {costClimbingStairs(dp, cost, i);}return dp[dp.length - 1];}public static void costClimbingStairs(int[] dp, int[] cost, int index) {if (dp[index - 1] + cost[index - 2] <= dp[index - 2] + cost[index - 3]) {dp[index] = dp[index - 1] + cost[index - 2];} else {dp[index] = dp[index - 2] + cost[index - 3];} }