本文主要是介绍Amber-Leedcode-Java - 代码随想录打卡第38 - 39天-动态规划汇总,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
509. 斐波那契数
较为简单
746. 使用最小花费爬楼梯
62. 不同路径
一开始写的时候被吓到了,但是发现听完一半之后再写还是比较容易的
对于我而言主要是找到逻辑,
class Solution {public int uniquePaths(int m, int n) {if (m <= 1 || n <=1){return 1;}int[][] result = new int[m][n];result[0][0] = 0;result[1][0] = 1;result[0][1] = 1;for (int i = 0;i < m;i++){for (int j = 0;j < n; j++){if (i > 0 && j > 0){result[i][j] = result[i][j-1] + result[i-1][j];}else if (i == 0 && j > 0 && j!=1){result[i][j] = result[i][j-1];}else if (j == 0 && i > 0 && i!=1){result[i][j] = result[i-1][j];}}}return result[m-1][n-1];
}
}
63. 不同路径 II
秒杀,和前者逻辑差不多,要注意初始化就好
class Solution {public int uniquePathsWithObstacles(int[][] obstacleGrid) {int m = obstacleGrid.length;int n = obstacleGrid[0].length;if (m <= 1 || n <=1){for (int i = 0;i < m; i++){for (int j = 0;j <n; j++){if (obstacleGrid[i][j] == 1){return 0;}}}return 1;}int[][] result = new int[m][n];if (obstacleGrid[0][0] == 1){return 0;}else{result[0][0] = 0;}if (obstacleGrid[1][0] == 1){result[1][0] = 0;}else{result[1][0] = 1;}if (obstacleGrid[0][1] == 1){result[0][1] = 0;}else{result[0][1] = 1;}for (int i = 0;i < m;i++){for (int j = 0;j < n; j++){if (obstacleGrid[i][j] == 1){result[i][j] = 0;}else if (i > 0 && j > 0){result[i][j] = result[i][j-1] + result[i-1][j];}else if (i == 0 && j > 0 && j!=1){result[i][j] = result[i][j-1];}else if (j == 0 && i > 0 && i!=1){result[i][j] = result[i-1][j];}}}return result[m-1][n-1];
}
}
别人的写法,比较nb
class Solution {public int uniquePathsWithObstacles(int[][] obstacleGrid) {int m = obstacleGrid.length;int n = obstacleGrid[0].length;int[][] dp = new int[m][n];//如果在起点或终点出现了障碍,直接返回0if (obstacleGrid[m - 1][n - 1] == 1 || obstacleGrid[0][0] == 1) {return 0;}for (int i = 0; i < m && obstacleGrid[i][0] == 0; i++) {dp[i][0] = 1;}for (int j = 0; j < n && obstacleGrid[0][j] == 0; j++) {dp[0][j] = 1;}for (int i = 1; i < m; i++) {for (int j = 1; j < n; j++) {dp[i][j] = (obstacleGrid[i][j] == 0) ? dp[i - 1][j] + dp[i][j - 1] : 0;}}return dp[m - 1][n - 1];}
}
343. 整数拆分
再写吧。。累了
这篇关于Amber-Leedcode-Java - 代码随想录打卡第38 - 39天-动态规划汇总的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!