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

dfs方法

输入:s = "abc"
输出:["abc","acb","bac","bca","cab","cba"]
class Solution:
    def permutation(self, s: str) -> List[str]:
        if not s:
            return s
        chars = sorted(list(s))
        path, permutations = [], []
        visited = [False]*len(chars)
        self.dfs(chars, visited, path, permutations)
        return permutations

    def dfs(self, chars, visited, path, permutations):
        if len(chars) == len(path):
            permutations.append(''.join(path))
            return
        for i in range(len(chars)):
            if visited[i]:    # 每次从头开始全局检索,必须要设置使用标志位
                continue
            # check is used
            if i>0 and chars[i-1]==chars[i] and visited[i-1]==False:
                continue
            path.append(chars[i])
            visited[i] = True
            self.dfs(chars, visited, path, permutations)
            path.pop()
            visited[i] = False

 

posted @ 2022-08-05 08:31  今夜无风  阅读(438)  评论(0编辑  收藏  举报