bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 131. Palindrome Partitioning

131. Palindrome Partitioning

Leetcode Solutions

Backtracking with Dynamic Programming

  1. Initialize a 2D array dp with dimensions n x n, where n is the length of the string s, to store palindrome information.
  2. Populate the dp array with true for all indices where i == j (single characters are palindromes) and for all indices where s[i] == s[j] and dp[i+1][j-1] is true (the characters at both ends match and the substring between them is a palindrome).
  3. Define a backtracking function backtrack(start, path) that explores all possible partitions starting from index start.
  4. If start reaches the end of the string, add the current path to the result.
  5. For each index i from start to the end of the string, check if s[start...i] is a palindrome by referring to dp[start][i].
  6. If it is a palindrome, append this substring to path and recursively call backtrack(i+1, path).
  7. After the recursive call, backtrack by removing the last substring added to path.
  8. Call backtrack(0, []) to start the backtracking process.
  9. Return the result containing all possible palindrome partitioning.
UML Thumbnail

Simple Backtracking

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...