[Leetcode] Palindrome Partitioning

本文介绍了一种使用深度优先搜索(DFS)实现的算法,该算法可以找出所有可能的回文字符串分割方式。通过递归地检查子串是否为回文,并在找到有效分割时记录结果,最终返回所有可能的分割方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a string s, partition s such that every substring of the partition is a palindrome.

Return all possible palindrome partitioning of s.

For example, given s = "aab",
Return

  [
    ["aa","b"],
    ["a","a","b"]
  ]

像这样列举所有结果的只能DFS了。不过为什么我老是忘记写++low跟--high呢,都死循环了自己还不知道!

 1 class Solution {
 2 public:
 3     bool isPail(string &s) {
 4         int low = 0, high = s.length() - 1;
 5         while (low < high) {
 6             if (s[low] != s[high]) {
 7                 return false;
 8             }
 9             ++low;
10             --high;
11         }
12         return true;
13     }
14     
15     void findNext(vector<vector<string> > &res, string &s, vector<string> part, int idx) {
16         if (idx == s.length()) {
17             res.push_back(part);
18             return;
19         }
20         string substr;
21         for (int len = s.length() - idx; len > 0; --len) {
22             substr = s.substr(idx, len);
23             if (isPail(substr)) {
24                 part.push_back(substr);
25                 findNext(res, s, part, idx + len);
26                 part.pop_back();
27             }
28         }
29     }
30     
31     vector<vector<string>> partition(string s) {
32         vector<vector<string> > res;
33         vector<string> part;
34         findNext(res, s, part, 0);
35         return res;
36     }
37 };

 

转载于:https://www.cnblogs.com/easonliu/p/3657733.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值