力扣练习——38 分割回文串

1.问题描述

给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。

返回 s 所有可能的分割方案的数量。

 

示例:

输入: "aab"

输出: 2

说明:可能的分割方案有:

[

  ["aa","b"],

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

]

2.输入说明

输入一个字符串 s,长度小于等于200.

3.输出说明

输出一个整数

4.范例

输入

aab

输出

2

5.代码

#include<iostream>
#include<algorithm>
#include<string>
#include<vector>
using namespace std;

vector<vector<string>>res;//结果数组
vector<string>temp;

bool isPalin(string s)
{
    int n = s.length();
    for (int i = 0; i < n/2; i++) //注意,这里只要遍历到一半即可
    {
        if (s[i] != s[n - 1 - i])
            return false;
    }
    return true;
}

void backtrace(string s, int index)
{
    int len = s.length();
    if (index == len)//遍历到结尾
    {
        res.push_back(temp);
        return;
    }
    for (int i = index; i < len; i++)
    {
        if (isPalin(s.substr(index, i - index + 1)))//重点理解下这里提取子串的操作
        {
            //访问到下标index,然后往后提取长度为1,2,etc的子串
            //当i==index时,提取子串长度为1
            temp.push_back(s.substr(index, i - index + 1));
            backtrace(s, i + 1);//遍历到下一个位置
            temp.pop_back();//回溯
        }
    }
}

int num_Partition(string s)
{
    int len = s.length();
    if (len == 0)
        return 1;
    //进行遍历回溯操作
    backtrace(s, 0);
    return res.size();
}

int main()

{
    string s;
    cin >> s;
    int res = num_Partition(s);
    cout << res << endl;
    return 0;
}

 

posted @ 2022-07-22 18:36  努力奋斗的小企鹅  阅读(42)  评论(0)    收藏  举报