剑指offer26.字符串的排列

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_36811967/article/details/86241828

https://www.nowcoder.com/practice/fe6b651b66ae47d7acce78ffdd9a96c7?tpId=13&tqId=11180&tPage=2&rp=2&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking

输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
输入描述:
输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。

用递归暴力求解,最后sort一下:

# -*- coding:utf-8 -*-
class Solution:
    def Permutation(self, ss):
        # write code here
        res = set()
        if ss == '':
            return res
        if len(ss) == 1:
            return [ss]
        for i, char in enumerate(ss):
            for j in self.Permutation(ss[:i]+ss[i+1:]):
                res.add(char+j)
        return sorted(list(res))

猜你喜欢

转载自blog.csdn.net/sinat_36811967/article/details/86241828