代码随想录算法训练营第二十三天-回溯算法-131. 分割回文串

  • 对字符串的分割,就是字符串下标的遍历
  • 下标就是分割标记
  • 这个题目的神奇之处就是它毫无特色,可以用以前几乎一模一样的回溯框架代码来套用
  • 但也就是看似与回溯毫无关联,但可以完美适用回溯代码,本身就是神奇所在
#include <iostream>
#include <vector>

class Solution {
private:
    std::vector<std::string> path;
    std::vector<std::vector<std::string>> result;
    bool isPalindrome(const std::string& str, int start, int end) {
        for (int i = start, j = end; i < j; ++i, --j)
            if(str[i] != str[j])
                return false;
        return true;
    }
    void backtracking(const std::string& str, int startIndex) {
        if (startIndex >= str.size()) {
            result.push_back(path);
            return;
        }
        for (int i = startIndex; i < str.size(); ++i) {
            if (isPalindrome(str, startIndex, i)) {
                std::string sub_str = str.substr(startIndex, i - startIndex + 1);
                path.push_back(sub_str);
            } else
                continue;
            backtracking(str, i + 1);
            path.pop_back();
        }
    }
public:
    std::vector<std::vector<std::string>> partition(std::string s) {
        backtracking(s, 0);
        return result;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值