题目内容
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
题目思路
这道题目我觉得可以考虑采用深度优先搜索的方式进行处理,构建一个DFS树,然后从根节点到叶节点的每一个不重复的序列组成了整个答案。
程序代码
# -*- coding:utf-8 -*-
class Solution:
def Permutation(self, ss):
# write code here
if not ss:
return []
res=[]
self.dfs(ss,res,'')
return res
def dfs(self,ss,res,tmp):
if not ss:
if tmp not in res:
res.append(tmp)
return
for i in range(len(ss)):
new_ss=ss[:i]+ss[i+1:]
self.dfs(new_ss,res,tmp+ss[i])