leetcode----63. Unique Paths II
链接:
https://leetcode.com/problems/unique-paths-ii/
大意:
给定一个二维整数矩阵,矩阵中的元素为0/1。1表示该位置是障碍位置。求出从起点(左上角)到达终点(右下角)有多少种方案?注意:无法越过障碍位置。例子:
思路:
和上一题思路一样:https://blog.****.net/smart_ferry/article/details/88894876
采用动态规划的解法。无法越过障碍位置==从起点到障碍位置的方案数为0.
代码:
class Solution {
public int uniquePathsWithObstacles(int[][] o) {
if (o.length == 0 || o[0][0] == 1)
return 0;
int[][] dp = new int[o.length + 1][o[0].length + 1];
dp[1][1] = 1;
for (int i = 1; i < dp.length; i++) {
for (int j = 1; j < dp[i].length; j++) {
if (i != 1 || j != 1) {
if (o[i - 1][j - 1] == 1)
dp[i][j] = 0;
else
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
}
}
//System.out.println(Arrays.deepToString(dp));
return dp[dp.length - 1][dp[0].length - 1];
}
}
结果:
结论:
动态规划:最优子结构+子问题重叠