添加 0131.分割回文串 Rust回溯+动态规划版本

添加 0131.分割回文串 Rust回溯+动态规划版本
This commit is contained in:
cezarbbb
2022-07-16 15:24:05 +08:00
parent c75fdf3dae
commit 4f867df86c

View File

@ -626,7 +626,8 @@ func partition(_ s: String) -> [[String]] {
## Rust
```rust
**回溯+函数判断回文串**
```Rust
impl Solution {
pub fn partition(s: String) -> Vec<Vec<String>> {
let mut ret = vec![];
@ -676,6 +677,40 @@ impl Solution {
}
}
```
**回溯+动态规划预处理判断回文串**
```Rust
impl Solution {
pub fn backtracking(is_palindrome: &Vec<Vec<bool>>, result: &mut Vec<Vec<String>>, path: &mut Vec<String>, s: &Vec<char>, 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::<String>()); } else { continue; }
Self::backtracking(is_palindrome, result, path, s, i + 1);
path.pop();
}
}
pub fn partition(s: String) -> Vec<Vec<String>> {
let mut result: Vec<Vec<String>> = Vec::new();
let mut path: Vec<String> = Vec::new();
let s = s.chars().collect::<Vec<char>>();
let len: usize = s.len();
// 使用动态规划预先打表
// 当且仅当其为空串(i>j)或其长度为1(i=j),或者首尾字符相同且(s[i+1..j1])时为回文串
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