LeetCode 131. Palindrome Partitioning

原题链接在这里:https://leetcode.com/problems/palindrome-partitioning/

题目:

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

Return all possible palindrome partitioning of s.

For example, given s = "aab",
Return

[
  ["aa","b"],
  ["a","a","b"]
]

题解:

backtracking问题, dfs时当前一段如果是Palindrome就加进item. 然后递归调用helper, 递归终止条件是能正好走到s.length().

Time Complexity: exponential. 

Space: O(res.size()).

AC Java:

 1 public class Solution {
 2     public List<List<String>> partition(String s) {
 3         List<List<String>> res = new ArrayList<List<String>>();
 4         if(s == null || s.length() == 0){
 5             return res;
 6         }
 7         helper(s,0, new ArrayList<String>(),res);  
 8         return res;
 9     }
10     private void helper(String s, int start,List<String> item, List<List<String>> res){
11         if(start == s.length()){
12             res.add(new ArrayList(item));
13             return;
14         }
15         StringBuilder sb = new StringBuilder();
16         for(int i = start; i <s.length(); i++){
17             sb.append(s.charAt(i));
18             if(isPalindrome(sb.toString())){
19                 item.add(sb.toString());
20                 helper(s,i+1,item,res);
21                 item.remove(item.size()-1);
22             }
23         }
24     }
25     private boolean isPalindrome(String s){
26         if(s == null || s.length() == 0){
27             return true;
28         }
29         int i = 0;
30         int j = s.length()-1;
31         while(i<j){
32             if(s.charAt(i) != s.charAt(j)){
33                 return false;
34             }
35             i++;
36             j--;
37         }
38         return true;
39     }
40 }

AC Python:

 1 class Solution:
 2     def partition(self, s: str) -> List[List[str]]:
 3         res = []
 4         if not s or len(s) == 0:
 5             return res
 6         
 7         self.dfs(s, 0, [], res)
 8         return res
 9     
10     def dfs(self, s, start, item, res):
11         if start == len(s):
12             res.append(item[:])
13             return
14         
15         for i in range(start, len(s)):
16             sub = s[start: i + 1]
17             if sub == sub[: : -1]:
18                 item.append(sub)
19                 self.dfs(s, i + 1, item, res)
20                 item.pop()

类似Word Break IISubsets.

跟上Palindrome Partitioning II.

posted @ 2015-09-13 02:22  Dylan_Java_NYC  阅读(285)  评论(0编辑  收藏  举报