27. 字符串的排列
题目描述
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
思路
递归法,问题转换为先固定第一个字符,求剩余字符的排列;求剩余字符排列时跟原问题一样。
遍历字符串,固定可能出现在第一个位置的字符,作为第一个字符,后面剩下的字符串的组合用递归使用本函数的方式得到。
代码实现
# -*- coding:utf-8 -*-
class Solution:
def Permutation(self, ss):
# write code here
length = len(ss)
if length <= 1:
return ss
lists = []
for i in range(length):
first_str = ss[i]
# 这里的ss[:i]+ss[i+1:] 刚好把ss[i]扣出来
for temp_sub_list in self.Permutation(ss[:i]+ss[i+1:]):
temp = first_str + temp_sub_list
if temp not in lists:
lists.append(temp)
return lists
京公网安备 11010502036488号