字符串的所有排列-python

在給定一個字符串ABC,輸出該字符串的所有排列組合 ABC ACB BAC BCA CAB CBA

鏈接:牛客原址

# 遞歸法
class Solution:
    def Permutation(self, ss):
        if len(ss) <= 1:
            return ss
        res = set()
        for i in range(len(ss)):
            # 每一個j是Permutation(ss[:i]+ss[i+1:])這個list中不同排列組合的一個strin
            # 每次迭代得獲得一個字符,最終獲得是所有的排列結果
            for j in self.Permutation(ss[:i]+ss[i+1:]):
                res.add(ss[i]+j)
        return sorted(res)
鏈接:https://www.nowcoder.com/questionTerminal/fe6b651b66ae47d7acce78ffdd9a96c7?orderByHotValue=0&commentTags=Python
來源:牛客網

class Solution:
    def Permutation(self, ss):
        if len(ss) <= 1:
            return ss
        res=set()
        tmp=[]
        # 用一個dict記住每個單詞出現次數
       counter = {}
        for s in ss:
            if s in counter:
            	counter[s] = 1
            else:
            	counter[s] += 1
        self.Back(res,tmp,ss,n_dict)
        return sorted(list(res))
    def Back(self,res,tmp,ss,counter):
        if len(tmp) == len(ss):
            print(tmp)
            print(len(ss))
            res.add(''.join(tmp))
        else:
            for i in ss:
                if counter[i] == 0:
                    continue
                # 用一次就減一,回溯時記得加回來
                counter[i] -= 1
                tmp.append(i)
                self.Back(res,tmp,ss,counter)
                counter[i] += 1
                tmp.pop()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章