leetcode 131. Palindrome Partitioning

本文介绍了一种使用回溯法解决回文串分割问题的方法,通过递归地检查字符串子集是否为回文来生成所有可能的分割方案。

摘要生成于 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”]
]

解题思路

这道题其实一眼看去就基本确定解法了,题目要求求出所有满足要求的回文串的组合,很明显这种题目可以采用回溯法求解,这里需要注意回溯过程,分解字符串时,考虑头部位置来分解,若分解部分是回文串,则递归调用回溯函数判断剩下的字符串是否是回文,leetcode上的高票解法并不直观,容易陷入下标困惑。下面是我写的解法,简洁易懂。

class Solution {
public:
    vector<vector<string>> partition(string s) {
        // backtrack
        vector<vector<string>> mVec;
        vector<string> sVec;
        backtrack(mVec,sVec,0,s);
        return mVec;
    }
    void backtrack(vector<vector<string>>& mVec,vector<string>& sVec,int start,string& s) {
        // test rest string s
        string restStr = s.substr(start);
        if(isPalindrome(restStr)) {
            auto tVec = sVec;
            tVec.push_back(restStr);
            mVec.push_back(tVec);

        }
        for(int i = start;i<s.size();++i) {
            string cs = s.substr(start,i-start+1);
            if(isPalindrome(cs)) {
                sVec.push_back(cs);
                backtrack(mVec,sVec,i+1,s);
                sVec.pop_back();
            }
        }
    }
    bool isPalindrome(const string& s) {
        if(s.empty()) return false;
        for(int i = 0,j = s.size()-1;i<j;++i,--j) {
            if(s[i]!=s[j]) return false;
        }
        return true;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值