Algo-Sim › Recursion & Backtracking

Palindrome Partitioning

Medium · Recursion & Backtracking · step through it in Java, Python and C++ on your own input

Every way to cut a string into palindromes: choose a palindromic first piece, recurse on the rest, and prune pieces that are not palindromes.

Problem

Cut the string s into pieces so that every piece is a palindrome. Return every possible way of doing so.

Constraints

Edge cases to test

Follow-up questions

How do you avoid re-checking palindromes?
Precompute isPal[i][j] with an O(n²) DP, so each check is O(1).
What about the fewest cuts?
A 1D DP over prefixes using isPal: O(n²) (LC 132).

Solution

Java

List<List<String>> result = new ArrayList<>();

List<List<String>> partition(String s) {
    backtrack(s, 0, new ArrayList<>());
    return result;
}

void backtrack(String s, int start, List<String> path) {
    if (start == s.length()) {
        result.add(new ArrayList<>(path));
        return;
    }
    for (int end = start + 1; end <= s.length(); end++) {
        String piece = s.substring(start, end);
        if (!isPalindrome(piece)) continue;
        path.add(piece);
        backtrack(s, end, path);
        path.remove(path.size() - 1);
    }
}

boolean isPalindrome(String t) {
    return new StringBuilder(t).reverse().toString().equals(t);
}

Python

def partition(s):
    result = []

    def backtrack(start, path):
        if start == len(s):
            result.append(path[:])
            return
        for end in range(start + 1, len(s) + 1):
            piece = s[start:end]
            if piece != piece[::-1]:
                continue
            path.append(piece)
            backtrack(end, path)
            path.pop()

    backtrack(0, [])
    return result

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    vector<vector<string>> result = {};

    vector<vector<string>> partition(string &s) {
        vector<string> path;
        backtrack(s, 0, path);
        return result;
    }

    void backtrack(string &s, int start, vector<string> &path) {
        if (start == int(s.size())) {
            result.push_back(path);
            return;
        }
        for (int end = start + 1; end <= int(s.size()); end++) {
            string piece = s.substr(start, (end) - (start));
            if (!isPalindrome(piece))
                continue;
            path.push_back(piece);
            backtrack(s, end, path);
            path.pop_back();
        }
    }

    bool isPalindrome(string &t) {
        return equal(t.begin(), t.end(), t.rbegin());
    }
};

More Recursion & Backtracking problems