131. Palindrome Partitioning
LeetCode 131. Palindrome Partitioning****
Description
Given a string s
, partition s
such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s
.
A palindrome string is a string that reads the same backward as forward.
Example 1:
Example 2:
Constraints:
1 <= s.length <= 16
s
contains only lowercase English letters.
Tags
Backtracking
Solution
Use the DFS template. Every time we examine the input string from the very first character to the whole string (Note: the index for traversal is from 1 to n, including n) if it is a palindrome. If it is, we append this substring to path
, then DFS the remaining string. The boundary contiditon is the input string is empty, and we append path
to the result 2D string slice.
Complexity
Time complexity: , the worst case happens when the input string is the same character repeated n times. Thus it has possible partitioning of
s
.Space complexity: , needs for path to store temporary result and stack space for recursion.
Code
Last updated
Was this helpful?