diff --git a/problems/0131.分割回文串.md b/problems/0131.分割回文串.md index 64d45853..a54d6576 100644 --- a/problems/0131.分割回文串.md +++ b/problems/0131.分割回文串.md @@ -626,7 +626,8 @@ func partition(_ s: String) -> [[String]] { ## Rust -```rust +**回溯+函数判断回文串** +```Rust impl Solution { pub fn partition(s: String) -> Vec> { let mut ret = vec![]; @@ -676,6 +677,40 @@ impl Solution { } } ``` +**回溯+动态规划预处理判断回文串** +```Rust +impl Solution { + pub fn backtracking(is_palindrome: &Vec>, result: &mut Vec>, path: &mut Vec, s: &Vec, start_index: usize) { + let len = s.len(); + if start_index >= len { + result.push(path.to_vec()); + return; + } + for i in start_index..len { + if is_palindrome[start_index][i] { path.push(s[start_index..=i].iter().collect::()); } else { continue; } + Self::backtracking(is_palindrome, result, path, s, i + 1); + path.pop(); + } + } + + pub fn partition(s: String) -> Vec> { + let mut result: Vec> = Vec::new(); + let mut path: Vec = Vec::new(); + let s = s.chars().collect::>(); + let len: usize = s.len(); + // 使用动态规划预先打表 + // 当且仅当其为空串(i>j),或其长度为1(i=j),或者首尾字符相同且(s[i+1..j−1])时为回文串 + let mut is_palindrome = vec![vec![true; len]; len]; + for i in (0..len).rev() { + for j in (i + 1)..len { + is_palindrome[i][j] = s[i] == s[j] && is_palindrome[i + 1][j - 1]; + } + } + Self::backtracking(&is_palindrome, &mut result, &mut path, &s, 0); + result + } +} +``` ## Scala