feat(geektime_algo): add 42 dynamic programming

edit_distance, longest_increasing_subsequence
This commit is contained in:
caitlin.gao 2019-09-05 13:55:55 +08:00
parent a7fad907af
commit 3e7b14e83e
2 changed files with 51 additions and 0 deletions

View 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);
}

View File

@ -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);
}