剑指offer 字符串的排列(全排列回溯、DFS)

描述

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

Solution 1 迭代

# -*- coding:utf-8 -*-
class Solution:
    def Permutation(self, ss):
        if not ss:
            return []
        ans, tmpans = [ss[0]], []
        for i in range(1, len(ss)):
            for item in ans:
                for j in range(len(item)+1):
                    # print(item)
                    tmp = item[:j]+ss[i]+item[j:]
                    if tmp not in tmpans:
                        tmpans.append(tmp)
            ans = tmpans
            tmpans = []
        ans.sort()
        return ans

Solution 2 回溯

全排列回溯。

class Solution:
    def Permutation(self, ss):
        n = len(ss)
        res = []
        def helper(s, tmp):
            if tmp and not s and tmp not in res:
                res.append(tmp[:])
            for i in range(len(s)):
                helper(s[:i]+s[i+1:], tmp+s[i])
        helper(ss, '')
        return res

Solution 3 DFS

常规DFS,注意返回返回数组进行去重、排序处理。

class Solution:
    def __init__(self):
        self.ss = ''
        self.visited = []
        self.tmpAns = []
        self.ans = []

    def Permutation(self, ss):
        self.ss = ss
        self.visited = [False for _ in self.ss]
        self.tmpAns = [None for _ in self.ss]
        if ss != '':
            self.DFS(0)
        res = [''.join(_) for _ in self.ans]
        res = list(set(res))
        res.sort()
        return res

    def DFS(self, curIndex):
        if curIndex == len(self.ss):
            self.ans.append(self.tmpAns[:])
            # print(self.tmpAns)
            return
        for index in range(len(self.ss)):
            if self.visited[index] == False:
                self.visited[index] = True
                self.tmpAns[curIndex] = self.ss[index]#index索引容易写错成curIndex
                self.DFS(curIndex+1)
                self.visited[index] = False

你可能感兴趣的:(牛客网,剑指,offer,算法----排列组合)