diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 0f3fd6f..288f268 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -510,3 +510,5 @@ mod p2502_design_memory_allocator; mod p1472_design_browser_history; mod p2353_design_a_food_rating_system; + +mod p131_palindrome_partitioning; diff --git a/src/problem/p131_palindrome_partitioning.rs b/src/problem/p131_palindrome_partitioning.rs new file mode 100644 index 0000000..d782026 --- /dev/null +++ b/src/problem/p131_palindrome_partitioning.rs @@ -0,0 +1,63 @@ +/** + * [131] Palindrome Partitioning + */ +pub struct Solution {} + +// submission codes start here + +impl Solution { + pub fn partition(s: String) -> Vec> { + let s: Vec = s.chars().collect(); + let length = s.len(); + + let mut result = vec![]; + let mut current: Vec = vec![]; + let mut dp = vec![vec![true; length]; length]; + + for i in (0..length).rev() { + for j in i + 1..length { + dp[i][j] = (s[i] == s[j]) && dp[i + 1][j - 1]; + } + } + + Self::dfs(&s, 0, &mut dp, &mut current, &mut result); + + result + } + + fn dfs( + s: &Vec, + pos: usize, + dp: &mut Vec>, + current: &mut Vec, + result: &mut Vec>, + ) { + if pos >= s.len() { + result.push(current.clone()); + return; + } + + for i in pos..s.len() { + if dp[pos][i] { + current.push(s[pos..i + 1].iter().collect()); + Self::dfs(s, i + 1, dp, current, result); + current.pop(); + } + } + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_131() { + assert_eq!( + vec![vec_string!("a", "a", "b"), vec_string!("aa", "b")], + Solution::partition("aab".to_owned()) + ); + } +}