Problem
Given a strings, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s.
Examples
Constraints
1 <= s.length <= 16scontains only lowercase English letters.
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 131 with 12 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 131 # by problem number
lcpy gen -s palindrome_partitioning # by problem name
s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s.
Input: s = "aab"
Output: [["a","a","b"],["aa","b"]]
Input: s = "a"
Output: [["a"]]
1 <= s.length <= 16s contains only lowercase English letters.class Solution:
# Time: O(N * 2^N)
# Space: O(N)
def partition(self, s: str) -> list[list[str]]:
result: list[list[str]] = []
self._backtrack(s, 0, [], result)
return result
def _backtrack(self, s: str, start: int, path: list[str], result: list[list[str]]) -> None:
if start == len(s):
result.append(path[:])
return
for end in range(start + 1, len(s) + 1):
substring = s[start:end]
if self._is_palindrome(substring):
path.append(substring)
self._backtrack(s, end, path, result)
path.pop()
def _is_palindrome(self, s: str) -> bool:
return s == s[::-1]
| Time | Space |
|---|---|
| O(N * 2^N) | O(N) |