2019.8.12 #程序员笔试必备# LeetCode 从零单刷个人笔记整理(持续更新)
假如用a和b标志将s分为三段,a之前是已经分割过的串,截至a一共有na种分割方案;a-b恰能构成一个回文串pal;b之后是未遍历的部分。那么在na种方案后分别加上pal可以形成截至b的na种方案,对于不断前进的每一个b,从0-b遍历所有a,每当a-b能够构成一个回文串时候,可以多出截至b的na种新方案。因此这道题可以用两种方法求解:
1.回溯法
从idx开始遍历每一位i,判断idx—i是否构成回文串,若构成回文串则继续递归遍历,遍历至结尾时存储方案。每层递归时需要将添加的子串去除,保持回溯。
2.动态规划
创建answer[i]用于存储从0开始至i-1位所有的回文子串序列,创建formBeginToEndIsPal[begin][end]代表s从begin-end是否为回文串。对于每一个end从头遍历每一位begin,如果从begin-end是回文串,将answer[begin]中的所有子串序列一次加上begin-end行成的新回文串,作为answer[end + 1]的回文子串序列。
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。
返回 s 所有可能的分割方案。
示例:
输入: "aab"
输出:
[
["aa","b"],
["a","a","b"]
]
import java.util.*;
/**
*
* Given a string s, partition s such that every substring of the partition is a palindrome.
* Return all possible palindrome partitioning of s.
* 给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。
* 返回 s 所有可能的分割方案。
*
*/
public class PalindromePartitioning {
//回溯法
List<List<String>> result = new LinkedList<>();
public List<List<String>> partition(String s) {
LinkedList<String> list = new LinkedList<>();
Solution(s, list, 0);
return result;