← Backtracking

Micro-Drill #191 — Palindrome partitioning backtrack

Backtracking Target: 15s

Try every prefix as a partition. If it's a palindrome, recurse on the rest. Enumerate all valid partitions.

def partition(s):
    res = []
    def backtrack(start, path):
        if start == len(s):
            res.append(path[:])
            return
        for end in range(start + 1, len(s) + 1):
            sub = s[start:end]
            if sub == sub[::-1]:
                path.append(sub)
                backtrack(end, path)
                path.pop()
    backtrack(0, [])
    return res

Type it from memory. Go.

Practice Problems

Related Coding Drills

← Micro #190 Micro #192 →