DevPath

← All problems

Palindrome Partitioning Count

Medium backtracking · strings · dynamic-programming

Description

Return the number of ways to partition the string so that every part is a palindrome.

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
}

Create a free account to submit solutions, track progress and save problems.

Create account