问题描述
给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。
返回 s 所有可能的分割方案。
示例:
输入: "aab"
输出:
[
["aa","b"],
["a","a","b"]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindrome-partitioning
解答
//backtrack class Solution { List<List<String>> res; public boolean check(String str,int left,int right){ while(left < right){ if(str.charAt(left) != str.charAt(right)){ return false; } left++; right--; } return true; } public void backtrack(int start, String s, Stack<String> output){ for(int i=start;i<s.length();i++){ String temp = s.substring(start, i+1); if(check(temp, 0, temp.length()-1)){ output.push(temp); if(i==s.length()-1)res.add(new ArrayList<String>(output)); backtrack(i+1, s, output); output.pop(); } } } public List<List<String>> partition(String s) { res = new ArrayList<List<String>>(); backtrack(0, s, new Stack<String>()); return res; } }