爽歪歪666
不以物喜,不以己悲,努力才是永恒的主题。

题目:

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

思路:

1.将字符串里的每个字符都充当一次第一个字符

2.固定第一个字符,剩余的字符串里每个字符都充当一次第二个字符

3.固定第二个字符,在剩余字符串中每个字符都充当一次第三个字符

依次递归......

代码实现

 1 class Solution:
 2     def Permutation(self, ss):
 3         if not ss:
 4             return []
 5         res = []
 6         self.perCore(ss, res, '')
 7         return sorted(set(res)) # 使用set去重,使用sorted按照字典序排序
 8 
 9     def perCore(self, ss, res, path):
10         if not ss:
11             res.append(path)
12         else:
13              for i in range(len(ss)):
14                 self.perCore(ss[:i] + ss[i+1:], res, path + ss[i])
15 if __name__ == '__main__':
16     str='123'
17     s= Solution()
18     print(s.Permutation(str))

递归过程详解

 

 参考了别人的代码:

https://blog.csdn.net/fuxuemingzhu/article/details/79513101

posted on 2020-04-21 16:50  爽歪歪666  阅读(491)  评论(0编辑  收藏  举报