[LeetCode]131. Palindrome Partitioning

131. Palindrome Partitioning

回溯

直接在s上进行操作。

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

返回值版本:

class Solution(object):
    def partition(self, s):
        """
        :type s: str
        :rtype: List[List[str]]
        """
        def backtracking(cur, path):
            if not cur:
                return True
            for i in range(len(cur)):
                temp = cur[:i+1]
                if temp == temp[::-1] and backtracking(cur[i+1:], path + [temp]):
                    res.append(path+[temp])
            return False
        res = []
        backtracking(s, [])
        return res

如果不想在s上进行操作,则用下标index纪录即可。

class Solution(object):
    def partition(self, s):
        """
        :type s: str
        :rtype: List[List[str]]
        """
        def backtracking(idx, path):
            if idx == len(s):
                res.append(path[:])
                return
            for i in range(idx, len(s)):
                temp = s[idx:i+1]
                if temp == temp[::-1]:
                    backtracking(i + 1, path + [temp])
        res = []
        backtracking(0, [])
        return res
posted @ 2017-08-30 17:06  banananana  阅读(87)  评论(0编辑  收藏  举报