Palindrome Partitioning--LeetCode

 

题目:

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

思路:我们从第一个字符开始直到最后一个字符,一旦有可以构造成回文的字符串,继续判断剩下的字符串是否可以构造成回文字符串。直到真个字符串都构造结束,输出构成的方式。使用一个向量记录构成的方式。

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

bool check(string& str,int begin,int end)
{
     int i = begin ;
     int j = end;
     for(;i<=j;i++,j--)
      if(str[i] != str[j])
        return false;
      return true;
}

void helper(string& str,int begin,int end,vector<int>& pos)
{
    int i,j,k;
    if(begin > end)
    {
        for(j=0;j<pos.size();j++)
        {
           cout<<str[j];
           if(pos[j] != -1)
           {
             cout<<",";
             pos[j] = -1;
           }                        
        }    
        cout<<endl;     
    }
    for(i= begin;i<=end;i++)
    {
        if(check(str,begin,i))
        {
            pos[i] = i-begin+1;
            helper(str,i+1,end,pos);  
        }  
    }     
}

void PalindromePartition(string& str)
{
     if(str.length() == 0)
      return ;
     vector<int> pos(str.length(),-1);
     helper(str,0,str.length()-1,pos);
}

int main()
{
    string str("aab");
    PalindromePartition(str);
    system("pause");
    return 0;
}
这也是一个典型的回溯问题,但是有的同学可能认为什么没有发现pos发生回溯的现象,也就是恢复原状的现象呢,因为在传递pos数组时传递的是已经分配好空间的数组,这个关于回溯使用这种方案,可以参考数据结构与算法系列中矩阵走的路径那个问题。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值