131. Palindrome Partitioning
Asked at 10Bloomberg59Amazon50Meta47Google46Microsoft46Infosys50Salesforce28Coupang68Visa48DE Shaw38
Problem
Split s into pieces that are all palindromes, and return every possible way to do so.
Example: "aab" → [["a","a","b"],["aa","b"]]
Constraints: length ≤ 16.
At index i, try every end j where s[i..j] is a palindrome, recurse from j+1. (Precompute a palindrome table to make checks O(1).)
Complexity: O(n · 2ⁿ).
class Solution:
def partition(self, s: str) -> List[List[str]]:
res, path = [], []
def bt(i):
if i == len(s):
res.append(path[:])
return
for j in range(i, len(s)):
piece = s[i:j + 1]
if piece == piece[::-1]:
path.append(piece)
bt(j + 1)
path.pop()
bt(0)
return res
assert sorted(Solution().partition("aab")) == sorted([["a", "a", "b"], ["aa", "b"]])
assert Solution().partition("a") == [["a"]]
assert sorted(Solution().partition("aba")) == [["a", "b", "a"], ["aba"]]
class Solution {
public List<List<String>> partition(String s) {
int n = s.length();
boolean[][] pal = new boolean[n][n];
for (int i = n - 1; i >= 0; i--)
for (int j = i; j < n; j++)
pal[i][j] = s.charAt(i) == s.charAt(j) && (j - i < 2 || pal[i + 1][j - 1]);
List<List<String>> res = new ArrayList<>();
bt(s, 0, pal, new ArrayList<>(), res);
return res;
}
private void bt(String s, int i, boolean[][] pal, List<String> path, List<List<String>> res) {
if (i == s.length()) { res.add(new ArrayList<>(path)); return; }
for (int j = i; j < s.length(); j++) {
if (!pal[i][j]) continue;
path.add(s.substring(i, j + 1));
bt(s, j + 1, pal, path, res);
path.remove(path.size() - 1);
}
}
}
func partition(s string) [][]string {
isPal := func(i, j int) bool {
for ; i < j; i, j = i+1, j-1 {
if s[i] != s[j] {
return false
}
}
return true
}
res, path := [][]string{}, []string{}
var bt func(i int)
bt = func(i int) {
if i == len(s) {
res = append(res, append([]string{}, path...))
return
}
for j := i; j < len(s); j++ {
if isPal(i, j) {
path = append(path, s[i:j+1])
bt(j + 1)
path = path[:len(path)-1]
}
}
}
bt(0)
return res
}