[LeetCode] 131. Palindrome Partitioning_Medium tag: DFS, backtracking, Palindrome

清疚 2021-11-16 07:20 314阅读 0赞

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

Return all possible palindrome partitioning of s.

Example:

  1. Input: "aab"
  2. Output:
  3. [
  4. ["aa","b"],
  5. ["a","a","b"]
  6. ]

这个题目我们可以理解为是s中不断决定是否要在该character的后面切一刀,可以切,可以不切, 2^n 种可能,让我们想到了subsets[LeetCode] 78. Subsets tag: backtracking,实际上就可以利用subsets的做法,只是temp存储的是s的index, 然后加上每切一刀的时候都要判断是否是palindrome,我们利用[Palindrome] Check any substring in a s is a palindrome or not. 来去优化时间复杂度。

T: O(2^n) 因为我们优化了palindrome substring。

Code

  1. class Solution:
  2. def palindromePartition(self, s):
  3. ans, palin = [], self.generatePalin(s)
  4. self.helper(s, [], 0, palin, ans)
  5. return ans
  6. def generatePalin(self, s):
  7. n = len(s)
  8. palin = [[False] * n for _ in range(n)]
  9. for i in range(n):
  10. palin[i][i] = True
  11. if i and s[i] == s[i - 1]:
  12. palin[i - 1][i] = True
  13. for length in range(2, n):
  14. for start in range(n):
  15. if start + length < n and s[start] == s[start + length]:
  16. palin[start][start + length] = palin[start + 1][start + length - 1]
  17. return palin
  18. def helper(self, s, temp, pos, palin, ans):
  19. if pos == len(s):
  20. ans.append(temp)
  21. for i in range(pos, len(s)):
  22. if not palin[pos][i]:
  23. continue
  24. self.helper(s, temp + [s[pos: i + 1]], i + 1, palin, ans)

转载于:https://www.cnblogs.com/Johnsonxiong/p/10921504.html

发表评论

表情:
评论列表 (有 0 条评论,314人围观)

还没有评论,来说两句吧...

相关阅读