Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 029e771

Browse files
Merge pull request youngyangyang04#1525 from cezarbbb/Backtracking01
添加 0131.分割回文串 Rust回溯+动态规划版本
2 parents d95cf01 + 4f867df commit 029e771

File tree

1 file changed

+36
-1
lines changed

1 file changed

+36
-1
lines changed

‎problems/0131.分割回文串.md

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -626,7 +626,8 @@ func partition(_ s: String) -> [[String]] {
626626

627627
## Rust
628628

629-
```rust
629+
**回溯+函数判断回文串**
630+
```Rust
630631
impl Solution {
631632
pub fn partition(s: String) -> Vec<Vec<String>> {
632633
let mut ret = vec![];
@@ -676,6 +677,40 @@ impl Solution {
676677
}
677678
}
678679
```
680+
**回溯+动态规划预处理判断回文串**
681+
```Rust
682+
impl Solution {
683+
pub fn backtracking(is_palindrome: &Vec<Vec<bool>>, result: &mut Vec<Vec<String>>, path: &mut Vec<String>, s: &Vec<char>, start_index: usize) {
684+
let len = s.len();
685+
if start_index >= len {
686+
result.push(path.to_vec());
687+
return;
688+
}
689+
for i in start_index..len {
690+
if is_palindrome[start_index][i] { path.push(s[start_index..=i].iter().collect::<String>()); } else { continue; }
691+
Self::backtracking(is_palindrome, result, path, s, i + 1);
692+
path.pop();
693+
}
694+
}
695+
696+
pub fn partition(s: String) -> Vec<Vec<String>> {
697+
let mut result: Vec<Vec<String>> = Vec::new();
698+
let mut path: Vec<String> = Vec::new();
699+
let s = s.chars().collect::<Vec<char>>();
700+
let len: usize = s.len();
701+
// 使用动态规划预先打表
702+
// 当且仅当其为空串(i>j),或其长度为1(i=j),或者首尾字符相同且(s[i+1..j−1])时为回文串
703+
let mut is_palindrome = vec![vec![true; len]; len];
704+
for i in (0..len).rev() {
705+
for j in (i + 1)..len {
706+
is_palindrome[i][j] = s[i] == s[j] && is_palindrome[i + 1][j - 1];
707+
}
708+
}
709+
Self::backtracking(&is_palindrome, &mut result, &mut path, &s, 0);
710+
result
711+
}
712+
}
713+
```
679714

680715

681716
## Scala

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /