Leet Code 63 Unique Paths II - 不同路径 - Java
2016-06-24 00:00
585 查看
摘要: Leet Code 63 Unique Paths II - 不同路径 - Java
问题原始链接 https://leetcode.com/problems/unique-paths-ii
该问题是 Unique Paths 的后续。
现在考虑网络中有一些障碍,有多少不同路径?
障碍用 1 表示,空格子用 0 表示。
例如,如下所示,3*3 的网络中间有一个障碍:
[
[0,0,0],
[0,1,0],
[0,0,0]
]
不同路径的总数为 2。
注意:m 和 n 最大为100。
问题原始链接 https://leetcode.com/problems/unique-paths-ii
该问题是 Unique Paths 的后续。
现在考虑网络中有一些障碍,有多少不同路径?
障碍用 1 表示,空格子用 0 表示。
例如,如下所示,3*3 的网络中间有一个障碍:
[
[0,0,0],
[0,1,0],
[0,0,0]
]
不同路径的总数为 2。
注意:m 和 n 最大为100。
public class Solution { public static int uniquePathsWithObstacles(int[][] obstacleGrid) { if (obstacleGrid == null || obstacleGrid.length == 0 || obstacleGrid[0].length == 0) { return 0; } if (obstacleGrid[0][0] != 0 || obstacleGrid[obstacleGrid.length - 1][obstacleGrid[0].length - 1] != 0) { return 0; } int[][] dp = new int[obstacleGrid.length][obstacleGrid[0].length]; dp[0][0] = 1; for (int j = 1; j < obstacleGrid[0].length; j++) { if (obstacleGrid[0][j] == 0 && dp[0][j - 1] == 1) { dp[0][j] = 1; } } for (int i = 1; i < obstacleGrid.length; i++) { if (obstacleGrid[i][0] == 0 && dp[i - 1][0] == 1) { dp[i][0] = 1; } } for (int i = 1; i < obstacleGrid.length; i++) { for (int j = 1; j < obstacleGrid[i].length; j++) { if (obstacleGrid[i][j] == 0) { dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; } } } return dp[obstacleGrid.length - 1][obstacleGrid[0].length - 1]; } }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解