Given a string s, partition s such that every substring of the partition is a palindrome.

Return all possible palindrome partitioning of s.

Example:

Input: "aab"
Output:
[
["aa","b"],
["a","a","b"]
]

解法1:dfs, 回溯Backchecking,

解法2:DP

Java:

public class Solution {
List<List<String>> resultLst;
ArrayList<String> currLst;
public List<List<String>> partition(String s) {
resultLst = new ArrayList<List<String>>();
currLst = new ArrayList<String>();
backTrack(s,0);
return resultLst;
}
public void backTrack(String s, int l){
if(currLst.size()>0 //the initial str could be palindrome
&& l>=s.length()){
List<String> r = (ArrayList<String>) currLst.clone();
resultLst.add(r);
}
for(int i=l;i<s.length();i++){
if(isPalindrome(s,l,i)){
if(l==i)
currLst.add(Character.toString(s.charAt(i)));
else
currLst.add(s.substring(l,i+1));
backTrack(s,i+1);
currLst.remove(currLst.size()-1);
}
}
}
public boolean isPalindrome(String str, int l, int r){
if(l==r) return true;
while(l<r){
if(str.charAt(l)!=str.charAt(r)) return false;
l++;r--;
}
return true;
}
}

Java: DP

public class Solution {
public static List<List<String>> partition(String s) {
int len = s.length();
List<List<String>>[] result = new List[len + 1];
result[0] = new ArrayList<List<String>>();
result[0].add(new ArrayList<String>()); boolean[][] pair = new boolean[len][len];
for (int i = 0; i < s.length(); i++) {
result[i + 1] = new ArrayList<List<String>>();
for (int left = 0; left <= i; left++) {
if (s.charAt(left) == s.charAt(i) && (i-left <= 1 || pair[left + 1][i - 1])) {
pair[left][i] = true;
String str = s.substring(left, i + 1);
for (List<String> r : result[left]) {
List<String> ri = new ArrayList<String>(r);
ri.add(str);
result[i + 1].add(ri);
}
}
}
}
return result[len];
}
}  

Python:

# Time:  O(2^n)
# Space: O(n)
# recursive solution
class Solution:
# @param s, a string
# @return a list of lists of string
def partition(self, s):
result = []
self.partitionRecu(result, [], s, 0)
return result def partitionRecu(self, result, cur, s, i):
if i == len(s):
result.append(list(cur))
else:
for j in xrange(i, len(s)):
if self.isPalindrome(s[i: j + 1]):
cur.append(s[i: j + 1])
self.partitionRecu(result, cur, s, j + 1)
cur.pop() def isPalindrome(self, s):
for i in xrange(len(s) / 2):
if s[i] != s[-(i + 1)]:
return False
return True

Python:

# Time:  O(n^2 ~ 2^n)
# Space: O(n^2)
# dynamic programming solution
class Solution:
# @param s, a string
# @return a list of lists of string
def partition(self, s):
n = len(s) is_palindrome = [[0 for j in xrange(n)] for i in xrange(n)]
for i in reversed(xrange(0, n)):
for j in xrange(i, n):
is_palindrome[i][j] = s[i] == s[j] and ((j - i < 2 ) or is_palindrome[i + 1][j - 1]) sub_partition = [[] for i in xrange(n)]
for i in reversed(xrange(n)):
for j in xrange(i, n):
if is_palindrome[i][j]:
if j + 1 < n:
for p in sub_partition[j + 1]:
sub_partition[i].append([s[i:j + 1]] + p)
else:
sub_partition[i].append([s[i:j + 1]]) return sub_partition[0]

Python: wo

class Solution(object):
def partition(self, s):
"""
:type s: str
:rtype: List[List[str]]
"""
res = []
self.helper(res, s, [], 0) return res def helper(self, res, s, cur, l):
if l == len(s):
res.append(list(cur))
return for r in range(l, len(s)):
if self.isPalindrome(s, l, r):
if l == r:
cur.append(s[l])
else:
cur.append(s[l:r+1])
self.helper(res, s, cur, r + 1)
cur.pop() def isPalindrome(self, s, l, r):
while l < r:
if s[l] != s[r]:
return False
l += 1
r -= 1
return True

Python:

class Solution(object):
def partition(self, s):
"""
:type s: str
:rtype: List[List[str]]
"""
res = []
self.dfs(s, [], res)
return res def dfs(self, s, path, res):
if not s:
res.append(path)
return
for i in range(1, len(s)+1):
if self.isPal(s[:i]):
self.dfs(s[i:], path+[s[:i]], res) def isPal(self, s):
return s == s[::-1]
res = []
self.helper(res, s, [], 0) return res

Python:

class Solution(object):
def partition(self, s):
"""
:type s: str
:rtype: List[List[str]]
"""
return [[s[:i]] + rest
for i in xrange(1, len(s)+1)
if s[:i] == s[i-1::-1]
for rest in self.partition(s[i:])] or [[]] 

C++:

class Solution {
public:
vector<vector<string>> partition(string s) {
vector<vector<string>> res;
vector<string> out;
partitionDFS(s, 0, out, res);
return res;
}
void partitionDFS(string s, int start, vector<string> &out, vector<vector<string>> &res) {
if (start == s.size()) {
res.push_back(out);
return;
}
for (int i = start; i < s.size(); ++i) {
if (isPalindrome(s, start, i)) {
out.push_back(s.substr(start, i - start + 1));
partitionDFS(s, i + 1, out, res);
out.pop_back();
}
}
}
bool isPalindrome(string s, int start, int end) {
while (start < end) {
if (s[start] != s[end]) return false;
++start;
--end;
}
return true;
}
};

  

 

类似题目:

[LeetCode] 132. Palindrome Partitioning II 回文分割 II 

All LeetCode Questions List 题目汇总

[LeetCode] 131. Palindrome Partitioning 回文分割的更多相关文章

  1. 131. Palindrome Partitioning(回文子串划分 深度优先)

    Given a string s, partition s such that every substring of the partition is a palindrome. Return all ...

  2. leetcode 131. Palindrome Partitioning 、132. Palindrome Partitioning II

    131. Palindrome Partitioning substr使用的是坐标值,不使用.begin()..end()这种迭代器 使用dfs,类似于subsets的题,每次判断要不要加入这个数 s ...

  3. [LeetCode] Valid Palindrome 验证回文字符串

    Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignori ...

  4. LeetCode Valid Palindrome 有效回文(字符串)

    class Solution { public: bool isPalindrome(string s) { if(s=="") return true; ) return tru ...

  5. [leetcode]131. Palindrome Partitioning字符串分割成回文子串

    Given a string s, partition s such that every substring of the partition is a palindrome. Return all ...

  6. [LeetCode] Shortest Palindrome 最短回文串

    Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it. ...

  7. leetcode 9 Palindrome Number 回文数

    Determine whether an integer is a palindrome. Do this without extra space. click to show spoilers. S ...

  8. [LeetCode] Prime Palindrome 质数回文数

    Find the smallest prime palindrome greater than or equal to N. Recall that a number is prime if it's ...

  9. [LeetCode] 266. Palindrome Permutation 回文全排列

    Given a string, determine if a permutation of the string could form a palindrome. Example 1: Input: ...

随机推荐

  1. scrapy框架用CrawlSpider类爬取电影天堂.

    本文使用CrawlSpider方法爬取电影天堂网站内国内电影分类下的所有电影的名称和下载地址 CrawlSpider其实就是Spider的一个子类. CrawlSpider功能更加强大(链接提取器,规 ...

  2. 转载:ubuntu系统启动顺序,常见系统服务说明

    Ubuntu运行级别Linux 系统任何时候都运行在一个指定的运行级上,并且不同的运行级的程序和服务都不同,所要完成的工作和要达到的目的都不同,系统可以在这些运行级之间进行切换,以完成不同的工作. 运 ...

  3. 通过iptables限制docker容器端口

    如何限制docker暴露的对外访问端口 docker 会在iptables上加上自己的转发规则,如果直接在input链上限制端口是没有效果的.这就需要限制docker的转发链上的DOCKER表. # ...

  4. 合并K个有序链表

    方法一:采用归并的思想将链表两两合并,再将两两合并后的链表做同样的操作直到合并为只有一个新的链表为止. 归类的时间复杂度是O(logn),合并两个链表的时间复杂度是O(n),则总的时间复杂度大概是O( ...

  5. Keil MDK5生成 .bin文件的简单教程(图文)

    以下参考https://blog.csdn.net/u014563989/article/details/51127519,同时自己实测. 1.按如图步骤做,主要是要找到fromelf.exe的路径: ...

  6. 字符串翻转(C++)

    1.字符串原地翻转,"abc"->"cba": int str_reverse(string &str,int first,int last) { ...

  7. BZOJ 4103: [Thu Summer Camp 2015]异或运算 可持久化trie

    开始想了一个二分+可持久化trie验证,比正解多一个 log 仔细思考,你发现你可以直接按位枚举,然后在可持久化 trie 上二分就好了. code: #include <bits/stdc++ ...

  8. CLR 调试概述

    利用公共语言运行时 (CLR) 调试 API,工具供应商可以编写调试器来调试运行于 CLR 环境中的应用程序. 要调试的代码可为 CLR 支持的任何代码种类.CLR 调试 API 主要是使用非托管代码 ...

  9. 14-ESP8266 SDK开发基础入门篇--上位机串口控制 Wi-Fi输出PWM的占空比,调节LED亮度,8266程序编写

    https://www.cnblogs.com/yangfengwu/p/11102026.html 首先规定下协议  ,CRC16就不加了哈,最后我会附上CRC16的计算程序,大家有兴趣自己加上 上 ...

  10. Java基础教程(全代码解析)

    字面量: 整数字面量为整型(int) 小数字面量为双精度浮点型(double) 数据类型: byte short int long float double 接下来代码展示理解 public clas ...