剑指offer 字符串的排列

题目

输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
输入描述:
输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。

思路

dfs

代码

# -*- coding:utf-8 -*-
class Solution:
    def __init__(self):
        self.res_list = []
    def dfs(self, num_list, index_list, numIndex, ss):
        num_list.append(ss[numIndex])
        index_list.append(numIndex)
        if len(num_list) == len(ss):
            res = ''.join(num_list[:])
            if res not in self.res_list:
                self.res_list.append(res)
        else:
            for i in range(len(ss)):
                if i in index_list:continue
                self.dfs(num_list, index_list, i, ss)
        index_list.pop(-1)
        num_list.pop(-1)
    def Permutation(self, ss):
        # write code here
        for i in range(len(ss)):
            self.dfs([], [], i, ss)
        return self.res_list

猜你喜欢

转载自blog.csdn.net/y12345678904/article/details/80752895