剑指offer-38.字符串的排列(或数字全排列)

题目来源:https://leetcode-cn.com/problems/zi-fu-chuan-de-pai-lie-lcof/

输入一个字符串,打印出该字符串中字符的所有排列。

你可以以任意顺序返回这个字符串数组,但里面不能有重复元素。

示例:

输入:s = "abc"
输出:["abc","acb","bac","bca","cab","cba"]

思路:

选定一个字符作为起始字符,其他字符全排列加到后面,所以显然这是一个递归问题。

解法一:排序去重

class Solution(object):
    def permutation(self, s):
        """
        :type s: str
        :rtype: List[str]
        """
        s = list(sorted(s))
        res = []
        def dfs(s, tmp):
            if not s:
                res.append(''.join(tmp))
                return 
            for i, c in enumerate(s):
                if i > 0 and s[i] == s[i-1]:     # 去重
                    continue
                dfs(s[:i] + s[i+1:], tmp + [c])
        dfs(s, [])
        return res

解法二:set去重

class Solution(object):
    def permutation(self, s):
        """
        :type s: str
        :rtype: List[str]
        """
        n = len(s)
        res = set()          # 去重
        def dfs(s, tmp):
            if not s:
                res.add(tmp)
                return
            for i, c in enumerate(s):
                dfs(s[:i] + s[i+1:], tmp + c)
        dfs(s, '')
        return list(res)

参考:

https://leetcode-cn.com/problems/zi-fu-chuan-de-pai-lie-lcof/solution/hui-su-fa-by-ai-wu-jin-xin-fei-xiang/

https://leetcode-cn.com/problems/zi-fu-chuan-de-pai-lie-lcof/solution/python3-di-gui-mei-ju-by-anakin/

你可能感兴趣的:(剑指offer-38.字符串的排列(或数字全排列))