Palindrome Partitioning Count
Medium backtracking · strings · dynamic-programming
Description
Constraints
1 <= length <= 15
Examples
Input: s = "aab"
Output: 2
aa|b and a|a|b
Hints (1)
- Recurse on prefixes that are palindromes.
Solutions
Backtracking over palindrome prefixes. · Time exponential · Space O(n)
func countPalindromePartitions(s string) int {
n := len(s)
var dfs func(start int) int
dfs = func(start int) int {
if start == n {
return 1
}
total := 0
for end := start; end < n; end++ {
if isPal(s, start, end) {
total += dfs(end + 1)
}
}
return total
}
return dfs(0)
}
func isPal(s string, i, j int) bool {
for i < j {
if s[i] != s[j] {
return false
}
i++
j--
}
return true
}
Backtracking over palindrome prefixes. · Time exponential · Space O(n)
function countPalindromePartitions(s) {
const n = s.length;
const isPal = (i, j) => {
while (i < j) { if (s[i] !== s[j]) return false; i++; j--; }
return true;
};
const dfs = (start) => {
if (start === n) return 1;
let total = 0;
for (let end = start; end < n; end++) if (isPal(start, end)) total += dfs(end + 1);
return total;
};
return dfs(0);
}
Backtracking over palindrome prefixes. · Time exponential · Space O(n)
function countPalindromePartitions($s) {
$n = strlen($s);
$isPal = function ($i, $j) use ($s) {
while ($i < $j) { if ($s[$i] !== $s[$j]) { return false; } $i++; $j--; }
return true;
};
$dfs = function ($start) use (&$dfs, &$isPal, $n) {
if ($start === $n) { return 1; }
$total = 0;
for ($end = $start; $end < $n; $end++) {
if ($isPal($start, $end)) { $total += $dfs($end + 1); }
}
return $total;
};
return $dfs(0);
}
Backtracking over palindrome prefixes. · Time exponential · Space O(n)
def countPalindromePartitions(s):
n = len(s)
def isPal(i, j):
while i < j:
if s[i] != s[j]:
return False
i += 1
j -= 1
return True
def dfs(start):
if start == n:
return 1
total = 0
for end in range(start, n):
if isPal(start, end):
total += dfs(end + 1)
return total
return dfs(0)
Backtracking over palindrome prefixes. · Time exponential · Space O(n)
function countPalindromePartitions(s: string): number {
const n = s.length;
const isPal = (i: number, j: number): boolean => {
while (i < j) { if (s[i] !== s[j]) return false; i++; j--; }
return true;
};
const dfs = (start: number): number => {
if (start === n) return 1;
let total = 0;
for (let end = start; end < n; end++) if (isPal(start, end)) total += dfs(end + 1);
return total;
};
return dfs(0);
}
Create a free account to submit solutions, track progress and save problems.
Create account