From 4f867df86c7ef1ba3ef2ae3858fc1f928025a070 Mon Sep 17 00:00:00 2001 From: cezarbbb <105843128+cezarbbb@users.noreply.github.com> Date: Sat, 16 Jul 2022 15:24:05 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200131.=E5=88=86=E5=89=B2?= =?UTF-8?q?=E5=9B=9E=E6=96=87=E4=B8=B2=20Rust=E5=9B=9E=E6=BA=AF+=E5=8A=A8?= =?UTF-8?q?=E6=80=81=E8=A7=84=E5=88=92=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0131.分割回文串 Rust回溯+动态规划版本 --- problems/0131.分割回文串.md | 37 +++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) 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