# 131\_ Palindrome Partitioning

\[Medium]\[String, Backtracking]

Given a string *s*, partition s such that every substring of the partition is a palindrome.

Return all possible palindrome partitioning of *s*.

**Example:**

```
Input: "aab"

Output:
[
  ["aa","b"],
  ["a","a","b"]
]
```

## Solution:

**Idea**:

* Focus on the first possible palindromic string in a partition.&#x20;
  * The first string itself is a valid palindromic partition.
  * Do a linear search to find all the possible palindromic substring starting from the first letter.
* Use recursion to deal with the left over.&#x20;

**Time Complexity**: $$O(n 2^n)$$ according to EPI page 236

**Space Complexity**: no extra space except for the output

```python
def partition(s):
    """
    :type s: str
    :rtype: List[List[str]]
    """
    def helper(offset, partial):
        # offset is the position of current string we are dealing with
        # partial is the substring that are already partitioned

        if offset == len(s):
            output.append(list(partial))  # list is not neccesary here
            return

        # case when s[offset] is partitioned
        helper(offset+1, partial+[s[offset]])

        # find the next palindrome candidate
        for i in range(offset+1, len(s)):
            if s[i] == s[offset]:
                if s[offset:i+1] == s[offset:i+1][::-1]:
                    helper(i+1, partial+[s[offset:i+1]])

    output = []
    helper(0, [])
    return output
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://lei-d.gitbook.io/leetcode/backtracking/131palindrome-partitioning.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
