【剑指offer 38】输入一个字符串,打印出该字符串中字符的所有排列。

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

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

示例:

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

class Solution(object):
    def permutation(self, s):
        """
        :type s: str
        :rtype: List[str]
        """
        c,res=list(s),[]
        def dfs(x):---x表示固定的字符位数
            if x ==len(c)-1:
                res.append(''.join(c))
                return
            dic=set()
            for i in range(x,len(c)):
                if c[i] in dic:----为了去重
                    continue
                dic.add(c[i])
                c[i],c[x]=c[x],c[i]----对列表中的元素进行交换
                dfs(x+1)---对下一位递归
                c[i],c[x]=c[x],c[i]----对交换的元素进行还原,保证列表中的元素是原来的顺序
        dfs(0)
        return res

  

原文地址:https://www.cnblogs.com/potato-chip/p/13784853.html