写点什么

代码随想录 Day39 - 动态规划(二)

作者:jjn0703
  • 2023-08-06
    江苏
  • 本文字数:1502 字

    阅读完需:约 5 分钟

作业题

62. 不同路径

初始化:dp[0][0~width] = 1, dp[0~height][0] = 1.

递推公式: dp[i][j] = dp[i - 1][j] + dp[i][j - 1] ( i>= 1, j >= 1)

package jjn.carl.dp;
import java.util.Scanner;
/** * @author Jjn * @since 2023/8/6 14:58 */public class LeetCode62 { public int uniquePaths(int m, int n) { int[][] dp = new int[m][n]; for (int i = 0; i < n; i++) { dp[0][i] = 1; } for (int i = 0; i < m; i++) { dp[i][0] = 1; } for (int i = 1; i < m; i++) { for (int j = 1; j < n; j++) { dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; } } return dp[m - 1][n - 1]; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int m = scanner.nextInt(); int n = scanner.nextInt(); int uniquePaths = new LeetCode62().uniquePaths(m, n); System.out.println(uniquePaths); }}
复制代码

63. 不同路径 II

初始化:dp[0][0~width] = 1, dp[0~height][0] = 1.

递推公式:

如果

obstacleGrid[i][j] == 0:

dp[i][j] = dp[i - 1][j] + dp[i][j - 1] ( i>= 1, j >= 1)

obstacleGrid[i][j] == 1:

dp[i][j] = 0

package jjn.carl.dp;
import jjn.round1.LeetCode171_ExcelSheetColumnNumber;
import java.util.Scanner;
/** * @author Jjn * @since 2023/8/6 15:04 */public class LeetCode63 { public int uniquePathsWithObstacles(int[][] obstacleGrid) { int height = obstacleGrid.length, width = obstacleGrid[0].length; int[][] dp = new int[height][width]; for (int i = 0; i < height; i++) { if (obstacleGrid[i][0] == 1) { for (int j = i; j < height; j++) { dp[j][0] = 0; i = j; } } else { dp[i][0] = 1; } } for (int i = 0; i < width; i++) { if (obstacleGrid[0][i] == 1) { for (int j = i; j < width; j++) { dp[0][j] = 0; i = j; } } else { dp[0][i] = 1; } } for (int i = 1; i < height; i++) { for (int j = 1; j < width; j++) { if (obstacleGrid[i][j] == 1) { dp[i][j] = 0; } else { dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; } } } return dp[height - 1][width - 1]; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int height = scanner.nextInt(); int width = scanner.nextInt(); int[][] obstacleGrid = new int[height][width]; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { obstacleGrid[i][j] = scanner.nextInt(); } } int uniquePathsWithObstacles = new LeetCode63().uniquePathsWithObstacles(obstacleGrid); System.out.println(uniquePathsWithObstacles); }}
复制代码


发布于: 刚刚阅读数: 3
用户头像

jjn0703

关注

Java工程师/终身学习者 2018-03-26 加入

USTC硕士/健身健美爱好者/Java工程师.

评论

发布
暂无评论
代码随想录Day39 - 动态规划(二)_jjn0703_InfoQ写作社区