Skip to content

Commit

Permalink
chore: add unique_paths_with_obstacles
Browse files Browse the repository at this point in the history
  • Loading branch information
zhangyuang committed Dec 31, 2020
1 parent 0e7e349 commit c8f00df
Show file tree
Hide file tree
Showing 4 changed files with 69 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,7 @@ Hot100类型题
[子集|subsets](./hot100/medium/subsets/src/lib.rs)
[零钱兑换|coin_change](./hot100/medium/coin_change/src/lib.rs)
[不同路径|unique_paths](./hot100/medium/unique_paths/src/lib.rs)
[不同路径 II|unique_paths_with_obstacles](./hot100/medium/unique_paths_with_obstacles/src/lib.rs)
[单词搜索|exist](./hot100/medium/exist/src/lib.rs)
[单词拆分|word_break](./hot100/medium/word_break/src/lib.rs)
[无重复字符的最长子串|length_of_longest_substring](./hot100/medium/length_of_longest_substring/src/lib.rs)
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
[package]
name = "leetcodebyrust"
version = "0.1.0"
authors = ["zhangyuang <yuuang>"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
54 changes: 54 additions & 0 deletions dynamic-programing/medium/unique_paths_with_obstacles/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/*
* @lc app=leetcode.cn id=63 lang=rust
*
* [63] 不同路径 II
*/
struct Solution {}
// @lc code=start
impl Solution {
pub fn unique_paths_with_obstacles(obstacle_grid: Vec<Vec<i32>>) -> i32 {
let m = obstacle_grid.len();
let n = obstacle_grid[0].len();
let mut dp = vec![vec![1; n]; m];
// 特殊处理第一列的情况
let mut hasObstacle = false;
for i in 0..n {
if obstacle_grid[0][i] == 1 {
hasObstacle = true
}
if hasObstacle {
dp[0][i] = 0
}
}
hasObstacle = false;
// 特殊处理第一行的情况
for i in 0..m {
if obstacle_grid[i][0] == 1 {
hasObstacle = true
}
if hasObstacle {
dp[i][0] = 0
}
}
for i in 1..m {
for j in 1..n {
let top = if obstacle_grid[i - 1][j] == 1 {
0
} else {
dp[i - 1][j]
};
let left = if obstacle_grid[i][j - 1] == 1 {
0
} else {
dp[i][j - 1]
};
dp[i][j] = top + left;
if obstacle_grid[i][j] == 1 {
dp[i][j] = 0
}
}
}
dp[m - 1][n - 1]
}
}
// @lc code=end

0 comments on commit c8f00df

Please sign in to comment.