面试题38. 字符串的排列

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

示例:
输入:s = “abc”
输出:[“abc”,“acb”,“bac”,“bca”,“cab”,“cba”]

思路

取出第i个数,全排列其他非i位置的数拼在后面

class Solution:
    def permutation(self, s: str) -> List[str]:
        length = len(s)
        if length == 0:
            return []
        if length == 1:
            return [s]
        res =[]
        for i in range(length):
            for j in self.permutation(s[:i]+s[i+1:]):
                if s[i]+j not in res:
                    res.append(s[i]+j)
        return res
发布了88 篇原创文章 · 获赞 31 · 访问量 5054

猜你喜欢

转载自blog.csdn.net/weixin_43455338/article/details/104976459