Skip to the content.

leetcode [面试题38] 字符串的排列


Contact me:

Blog -> https://cugtyt.github.io/blog/index
Email -> cugtyt@qq.com
GitHub -> Cugtyt@GitHub


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

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

示例:

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

来自题解:

class Solution:
    def permutation(self, s: str) -> List[str]:
        def helper(s):
            if len(s) == 1:
                return s
            res = []
            for i in range(len(s)):
                l = helper(s[:i] + s[i+1:])
                for j in l:
                    res.append(s[i] + j)
            return res
        
        if not s: return []
        return set(helper(s))