剑指offer全集详解python版——字符串的排列

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

题目描述:
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。

思路:

经典的回溯法。

代码:

# -*- coding:utf-8 -*-
class Solution:
    def Permutation(self, ss):
        # write code here
        if len(ss) <=0:
            return []
        res = list()
        self.perm(ss,res,'')
        uniq = list(set(res))
        return sorted(uniq)
    def perm(self,ss,res,path):
        if ss=='':
            res.append(path)
        else:
            for i in range(len(ss)):
                self.perm(ss[:i]+ss[i+1:],res,path+ss[i])

猜你喜欢

转载自blog.csdn.net/weixin_41679411/article/details/86487931