剑指offer 38 - 字符串的排列 - python

103 阅读1分钟

题目描述:

输入一个字符串,打印出该字符串中字符的所有排列。你可以以任意顺序返回这个字符串数组,但里面不能有重复元素。

示例:

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

限制:1 <= s 的长度 <= 8

来源:力扣(LeetCode)


AC代码

直接使用回溯模版解题即可。另外由于字符串中可以存在相同的字符,可以先将字符串按字典序排序,然后在回溯过程中加入相应的剪枝操作,从而减少回溯的过程。

class Solution:
    def permutation(self, s: str) -> List[str]:
        if s is None: return []
        
        l = len(s)
        r = []
        def track(s, path):
        	# 出口
            if len(path) == l:
                r.append(''.join(path))
                return

            for i in range(len(s)):
                # 字符串中可能存在重复字符,剪枝
                if i > 0 and s[i] == s[i - 1]:
                    continue
                # 做选择
                path.append(s[i])
                track(s[:i] + s[i+1:], path)
                # 撤销选择
                path.pop()
            
        s = list(sorted(s))
        track(s, [])

        return r