• [LeetCode] 131. 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.

    Example:

    Input: "aab"
    Output:
    [
      ["aa","b"],
      ["a","a","b"]
    ]

    解法1:dfs, 回溯Backchecking,

    解法2:DP

    Java:

    public class Solution {
            List<List<String>> resultLst;
    	    ArrayList<String> currLst;
    	    public List<List<String>> partition(String s) {
    	        resultLst = new ArrayList<List<String>>();
    	        currLst = new ArrayList<String>();
    	        backTrack(s,0);
    	        return resultLst;
    	    }
    	    public void backTrack(String s, int l){
    	        if(currLst.size()>0 //the initial str could be palindrome
    	            && l>=s.length()){
    	                List<String> r = (ArrayList<String>) currLst.clone();
    	                resultLst.add(r);
    	        }
    	        for(int i=l;i<s.length();i++){
    	            if(isPalindrome(s,l,i)){
    	                if(l==i)
    	                    currLst.add(Character.toString(s.charAt(i)));
    	                else
    	                    currLst.add(s.substring(l,i+1));
    	                backTrack(s,i+1);
    	                currLst.remove(currLst.size()-1);
    	            }
    	        }
    	    }
    	    public boolean isPalindrome(String str, int l, int r){
    	        if(l==r) return true;
    	        while(l<r){
    	            if(str.charAt(l)!=str.charAt(r)) return false;
    	            l++;r--;
    	        }
    	        return true;
    	    }
    }
    

    Java: DP

    public class Solution {
     	public static List<List<String>> partition(String s) {
    		int len = s.length();
    		List<List<String>>[] result = new List[len + 1];
    		result[0] = new ArrayList<List<String>>();
    		result[0].add(new ArrayList<String>());
    
    		boolean[][] pair = new boolean[len][len];
    		for (int i = 0; i < s.length(); i++) {
    			result[i + 1] = new ArrayList<List<String>>();
    			for (int left = 0; left <= i; left++) {
    				if (s.charAt(left) == s.charAt(i) && (i-left <= 1 || pair[left + 1][i - 1])) {
    					pair[left][i] = true;
    					String str = s.substring(left, i + 1);
    					for (List<String> r : result[left]) {
    						List<String> ri = new ArrayList<String>(r);
    						ri.add(str);
    						result[i + 1].add(ri);
    					}
    				}
    			}
    		}
    		return result[len];
    	}
    }  

    Python:

    # Time:  O(2^n)
    # Space: O(n)
    # recursive solution
    class Solution:
        # @param s, a string
        # @return a list of lists of string
        def partition(self, s):
            result = []
            self.partitionRecu(result, [], s, 0)
            return result
    
        def partitionRecu(self, result, cur, s, i):
            if i == len(s):
                result.append(list(cur))
            else:
                for j in xrange(i, len(s)):
                    if self.isPalindrome(s[i: j + 1]):
                        cur.append(s[i: j + 1])
                        self.partitionRecu(result, cur, s, j + 1)
                        cur.pop()
    
        def isPalindrome(self, s):
            for i in xrange(len(s) / 2):
                if s[i] != s[-(i + 1)]:
                    return False
            return True
    

    Python:

    # Time:  O(n^2 ~ 2^n)
    # Space: O(n^2)
    # dynamic programming solution
    class Solution:
        # @param s, a string
        # @return a list of lists of string
        def partition(self, s):
            n = len(s)
    
            is_palindrome = [[0 for j in xrange(n)] for i in xrange(n)]
            for i in reversed(xrange(0, n)):
                for j in xrange(i, n):
                    is_palindrome[i][j] = s[i] == s[j] and ((j - i < 2 ) or is_palindrome[i + 1][j - 1])
    
            sub_partition = [[] for i in xrange(n)]
            for i in reversed(xrange(n)):
                for j in xrange(i, n):
                    if is_palindrome[i][j]:
                        if j + 1 < n:
                            for p in sub_partition[j + 1]:
                                sub_partition[i].append([s[i:j + 1]] + p)
                        else:
                            sub_partition[i].append([s[i:j + 1]])
    
            return sub_partition[0]
    

    Python: wo

    class Solution(object):
        def partition(self, s):
            """
            :type s: str
            :rtype: List[List[str]]
            """
            res = []
            self.helper(res, s, [], 0)
            
            return res
            
        def helper(self, res, s, cur, l):
            if l == len(s):
                res.append(list(cur))
                return
                
            for r in range(l, len(s)):
                if self.isPalindrome(s, l, r):
                    if l == r:
                        cur.append(s[l])
                    else:
                        cur.append(s[l:r+1])
                    self.helper(res, s, cur, r + 1)
                    cur.pop()     
            
        def isPalindrome(self, s, l, r):
            while l < r:
                if s[l] != s[r]:
                    return False
                l += 1
                r -= 1
            return True 
    

    Python:

    class Solution(object):
        def partition(self, s):
            """
            :type s: str
            :rtype: List[List[str]]
            """
            res = []
            self.dfs(s, [], res)
            return res
    
        def dfs(self, s, path, res):
            if not s:
                res.append(path)
                return
            for i in range(1, len(s)+1):
                if self.isPal(s[:i]):
                    self.dfs(s[i:], path+[s[:i]], res)
    
        def isPal(self, s):
            return s == s[::-1]
                res = []
                self.helper(res, s, [], 0)
    
                return res
    

    Python:

    class Solution(object):
        def partition(self, s):
            """
            :type s: str
            :rtype: List[List[str]]
            """
            return [[s[:i]] + rest
                    for i in xrange(1, len(s)+1)
                    if s[:i] == s[i-1::-1]
                    for rest in self.partition(s[i:])] or [[]] 

    C++:

    class Solution {
    public:
        vector<vector<string>> partition(string s) {
            vector<vector<string>> res;
            vector<string> out;
            partitionDFS(s, 0, out, res);
            return res;
        }
        void partitionDFS(string s, int start, vector<string> &out, vector<vector<string>> &res) {
            if (start == s.size()) {
                res.push_back(out);
                return;
            }
            for (int i = start; i < s.size(); ++i) {
                if (isPalindrome(s, start, i)) {
                    out.push_back(s.substr(start, i - start + 1));
                    partitionDFS(s, i + 1, out, res);
                    out.pop_back();
                }
            }
        }
        bool isPalindrome(string s, int start, int end) {
            while (start < end) {
                if (s[start] != s[end]) return false;
                ++start;
                --end;
            }
            return true;
        }
    };
    

      

     

    类似题目:

    [LeetCode] 132. Palindrome Partitioning II 回文分割 II 

    All LeetCode Questions List 题目汇总

  • 相关阅读:
    asp.net中的窗体身份验证(不同的角色访问不同的目录)
    asp.net中的窗体身份验证(完整篇之六:登出后不能通过后退回来面来的页面)
    asp.net中的窗体身份验证(完整篇之一:创建asp.net的窗体身份验证方式)
    asp.net中的窗体身份验证(完整篇之四:获得用户数据)
    asp.net中的窗体身份验证(完整篇之五:退出登录)
    [iphone]UIImage,CGImage和CGImageRef有什么区别
    glVertexAttribPointer
    在OpenGL中使用着色器的步骤
    glViewport()函数和glOrtho()函数的理解
    OpenGL ES 三种类型修饰 uniform attribute varying
  • 原文地址:https://www.cnblogs.com/lightwindy/p/9627845.html
Copyright © 2020-2023  润新知