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

思路:

回溯,但是不是常规回溯,因为解向量大小不定,需要动态判断。 下面是我写的代码, 只用了19ms 非常快, 自己挺满意的。

感受:之前做过DP求最少切几刀令所有部分都是回文,跟这个有点像。 觉得凡是求最的都是用DP,凡是求所有解的都是用回溯。

class Solution {
public:
vector<vector<string>> partition(string s) {
vector<vector<string>> ans;
if(s.empty())
return ans; vector<vector<bool>> isPalindrome(s.length(), vector<bool>(s.length(), false));
vector<vector<int>> S(s.length(), vector<int>(, )); //每个深度候选范围 用下标范围来记录
int k = ;
vector<string> X; while(k >= )
{
while(k >= && S[k][] < s.length()) //当前深度判断完毕 通过当前范围结束下标到达s的最后
{
int i = S[k][]; //当前深度判断位置的起始下标
int j = S[k][]; //当前深度判断位置的结束下标
if(s[i] == s[j] && (j - i < || isPalindrome[i+][j - ])) //分次判断是否为回文,每次使用历史信息
{
isPalindrome[i][j] = true;
while(X.size() >= k + ) //X长度不固定,所以用的时候会有上一次求解的值,我们需要把多出的部分弹出 !!特别注意
{
X.pop_back();
}
X.push_back(s.substr(i, j - i + ));
S[k][]++;
if(S[k][] < s.length())
{
k++;
S[k][] = S[k - ][];
S[k][] = S[k - ][];
}
else
{
ans.push_back(X);
}
}
else
{
S[k][]++;
}
}
k--;
}
return ans;
}
};

随机推荐

  1. 低版本IE浏览器 input元素出现叉叉的情况

    都说是IE10之上的浏览器才有这个问题,恰巧我IE10之上都没有问题,反而是低版本的浏览器出现了这个问题.作为一个凭证,我先放一张图片在这里面. 之前无意中解决过这个问题,如今复现确实是没有解决,网上 ...

  2. Python-时间操作

    目录 Python标准模块 datetime 数据类型 datetime timedelta 字符串和datetime的相互转换 datetime 转 字符串 str strftime strftim ...

  3. Hadoop 之MongoDB

    NoSql 简介: COUCH DB REDIS MONGODB NEO4J HBASE BIGTABLE 存储非结构化数据 索引多:单键,多键,数组,全文,2D. MonggoDB数据类型: nul ...

  4. CentOS编译安装Apache 2.4.x时报错:configure: error: Bundled APR requested but not found at ./srclib/. Download and unpack the corresponding apr and apr-util packages to ./srclib/.

    先前按照这篇文章“CentOS6.x编译安装LAMP(2):编译安装 Apache2.2.22”去编译安装Apache2.2.x版本时,安装得挺顺利,今天换成Apache2.4.x版本,安装方法一样, ...

  5. javaweb 解决将ajax返回的内容用document.write写入,FireFox一直加载的问题

    在document.write方法后加上document.close就解决了, 想知道原理的小伙伴可以继续看 浏览器在解析html时会打开一个流,这是用document.write中写入,是加入当解析 ...

  6. leetcode 142. Linked List Cycle II

    Given a linked list, return the node where the cycle begins. If there is no cycle, return null. Note ...

  7. [BZOJ3991][SDOI2015]寻宝游戏

    [BZOJ3991][SDOI2015]寻宝游戏 试题描述 小B最近正在玩一个寻宝游戏,这个游戏的地图中有N个村庄和N-1条道路,并且任何两个村庄之间有且仅有一条路径可达.游戏开始时,玩家可以任意选择 ...

  8. 移动前端头部mete

    原文链接:http://caibaojian.com/mobile-meta.html//code from http://caibaojian.com/mobile-meta.html<!DO ...

  9. python 内置速度最快算法(堆排)

    import random import time from heapq import heappush, heappop def heapsort(iterable): h = [] for val ...

  10. Droid4x安装busybox

      下载Busybox                                                                                         ...