题目
题目描述
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
示例1
输入
“abc”
返回值
[‘abc’, ‘acb’, ‘bac’, ‘bca’, ‘cab’, ‘cba’]
一、思路
【思路】
把字符串分为两部分:一部分是字符串的第一个字符,另一部分是第一个字符以后的所有字符。
- 第一步是求所有可能出现在第一个位置的字符,即把第一个字符和后面所有字符交换。(for循环、交换操作)
- 第二步是固定住第一个字符,求后面所有字符的排列。(递归)
- 而“求后面所有字符的排列”即可按照上面的思路递归进行。
二、代码
# -*- coding:utf-8 -*-
class Solution:
def Permutation(self, ss):
# write code here
str_list=[x for x in ss]
ret=[]
self.construct(str_list,'',ret)
uniq=list(set(ret))
uniq.sort()
return uniq
def construct(self,str_list,buf,ret):
if not str_list and buf:
ret.append(buf)
return
for i in range(len(str_list)):
self.construct(str_list[:i]+str_list[i+1:],buf+str_list[i],ret)