From 4b241b0a42b7bc1c43c5de343cba1da0929bc0f9 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Mon, 3 Mar 2025 14:01:45 +0800 Subject: [PATCH] 20250303 finished. --- src/problem/mod.rs | 2 + .../p1278_palindrome_partitioning_iii.rs | 60 +++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 src/problem/p1278_palindrome_partitioning_iii.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 4bfe421..aab7c22 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -514,3 +514,5 @@ mod p2353_design_a_food_rating_system; mod p131_palindrome_partitioning; mod p132_palindrome_partitioning_ii; + +mod p1278_palindrome_partitioning_iii; diff --git a/src/problem/p1278_palindrome_partitioning_iii.rs b/src/problem/p1278_palindrome_partitioning_iii.rs new file mode 100644 index 0000000..acf7ada --- /dev/null +++ b/src/problem/p1278_palindrome_partitioning_iii.rs @@ -0,0 +1,60 @@ +/** + * [1278] Palindrome Partitioning III + */ +pub struct Solution {} + +// submission codes start here + +impl Solution { + pub fn palindrome_partition(s: String, k: i32) -> i32 { + let s: Vec = s.chars().collect(); + let length = s.len(); + + // cost[i][j] + // 将 s[i..=j] 修改为回文串需要的修改次数 + let mut cost = vec![vec![0; length]; length]; + + for span in 2..=length { + for i in 0..=length - span { + let j = i + span - 1; + + cost[i][j] = cost[i + 1][j - 1] + if s[i] == s[j] { 0 } else { 1 }; + } + } + + let k = k as usize; + // dp[i][j] + // 将s[..i]分割为j个回文串需要的修改次数 + let mut dp = vec![vec![i32::MAX; k + 1]; length + 1]; + + for i in 1..=length { + for j in 1..=i.min(k) { + if j == 1 { + dp[i][j] = cost[0][i - 1]; + } else { + // 这里k从j - 1开始枚举是因为前面需要进行j - 1次分割时 + // 字符串的长度必须大于等于j - 1 + for k in j - 1..i { + dp[i][j] = dp[i][j].min(dp[k][j - 1] + cost[k][i - 1]); + } + } + } + } + + dp[length][k] + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1278() { + assert_eq!(1, Solution::palindrome_partition("abc".to_owned(), 2)); + assert_eq!(0, Solution::palindrome_partition("aabbc".to_owned(), 3)); + assert_eq!(0, Solution::palindrome_partition("leetcode".to_owned(), 8)); + } +}