剑指Offer(Python语言)面试题38

面试题38:字符串的排列

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

# -*- coding:utf-8 -*-
class Solution:
    def Permutation(self, ss):
        # write code here
        ss = list(ss)
        result = []
        if not ss:
            return []
        self.permutation(ss,0,result)
        result = sorted(result)
        return result
    def permutation(self, ss, begin, result):
        if begin == len(ss)-1:
            result.append("".join(ss))
        for i in range(begin, len(ss)):
            if i!=begin and ss[i]==ss[begin]:
                continue
            ss[begin],ss[i] = ss[i], ss[begin]
            self.permutation(ss,begin+1,result)
            ss[begin],ss[i] = ss[i], ss[begin]

 

你可能感兴趣的:(剑指offer)