feat(geektime_algo): add 42 dynamic programming
edit_distance, longest_increasing_subsequence
This commit is contained in:
parent
a7fad907af
commit
3e7b14e83e
29
rust/42_dynamic_programming/edit_distance.rs
Normal file
29
rust/42_dynamic_programming/edit_distance.rs
Normal file
@ -0,0 +1,29 @@
|
|||||||
|
// leetcode 72 [edit_distance](https://leetcode.com/problems/edit-distance/)
|
||||||
|
fn edit_distance(word1: &str, word2: &str) -> i32 {
|
||||||
|
let word1_chars: Vec<char> = word1.chars().collect();
|
||||||
|
let word2_chars: Vec<char> = word2.chars().collect();
|
||||||
|
let m = word1.len();
|
||||||
|
let n = word2.len();
|
||||||
|
let mut dp = vec![vec![0; m+1]; n+1];
|
||||||
|
|
||||||
|
// 初始化第一行
|
||||||
|
for i in 0..=m { dp[i][0] = i; }
|
||||||
|
// 初始化第一列
|
||||||
|
for j in 0..=n { dp[0][j] = j; }
|
||||||
|
|
||||||
|
for i in 1..=m {
|
||||||
|
for j in 1..=n {
|
||||||
|
let mut step = 0;
|
||||||
|
if word1_chars[i-1] != word2_chars[j-1] { step = 1; }
|
||||||
|
dp[i][j] = (dp[i][j-1] + 1).min(dp[i-1][j] + 1).min(dp[i-1][j-1] + step);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
dp[m][n] as i32
|
||||||
|
}
|
||||||
|
fn main() {
|
||||||
|
let word1 = "mitcmu";
|
||||||
|
let word2 = "mtacnu";
|
||||||
|
let m = edit_distance(word1, word2);
|
||||||
|
println!("{:?}", m);
|
||||||
|
}
|
@ -0,0 +1,22 @@
|
|||||||
|
// leetcode 300 [longest_increasing_subsequence](https://leetcode.com/problems/longest-increasing-subsequence)
|
||||||
|
fn longest_increasing_subsequence(nums: Vec<i32>) -> i32 {
|
||||||
|
if nums.len() <= 1 { return nums.len() as i32; }
|
||||||
|
|
||||||
|
let mut dp = vec![1; nums.len()];
|
||||||
|
let mut max_list = 1;
|
||||||
|
|
||||||
|
for i in 0..nums.len() {
|
||||||
|
for j in 0..i {
|
||||||
|
if nums[i] > nums[j] {
|
||||||
|
dp[i] = dp[i].max(dp[j]+1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
max_list = max_list.max(dp[i]);
|
||||||
|
}
|
||||||
|
max_list
|
||||||
|
}
|
||||||
|
fn main() {
|
||||||
|
let nums = vec![2, 9, 3, 6, 5, 1, 7];
|
||||||
|
let m = longest_increasing_subsequence(nums);
|
||||||
|
println!("{:?}", m);
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user