LeetCode 131. Palindrome Partitioning--回溯法

本文详细介绍了如何使用回溯法解决字符串的回文分割问题,包括编写判断回文的函数和实现递归分割的逻辑。通过示例代码展示了完整的解决方案。

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

题目链接

131. Palindrome Partitioning

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"]
]

解:回溯法“套路”按部就班:

1.写一个判断函数 isPalindrome ,判断字符串是不是palindrome(回文(指顺读和倒读都一样的词语)

2.写一个递归函数 split ,参数 head 代表从 head 位置开始找所有能构成回文的字符串(第一个一定是head位置的字符本身),找到后将子串放入 vector 中,再次调用 split 在子串尾位置开始找,当找到所有情况后,即将子串从 vector 中 pop 出。终止递归函数的条件就是当位置 head 已经超过了字符串的长度,这时候我们得到了一个解,将得到的 vector 放进结果 vector<vector> 后直接返回。

3. partition 中调用递归函数 split ,参数 head = 0

代码:

class Solution {
public:
    bool isPalindrome(int head, int tail, string origin) {
        while (head < tail) {
            if (origin[head] != origin[tail]) return false;
            head++;
            tail--;
        }
        return true;
    }

    void split(string str, int head, vector<string>& temp, vector<vector<string> >& all) {
        int len = str.length();
        if (head >= len) {
            vector<string> copy;
            copy.assign(temp.begin(), temp.end());
            all.push_back(copy);
            return;
        }
        for (int i = head; i < len; i++) {
            if (isPalindrome(head, i, str)) {
                temp.push_back(str.substr(head, i-head+1));
                split(str, i+1, temp, all);
                temp.pop_back();
            }
        }
        return;
    }

    vector<vector<string> > partition(string s) {
        vector<vector<string> > answer;
        vector<string> temp;
        split(s, 0, temp, answer);
        return answer;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值