题解 | #字符串的排列#
字符串的排列
http://www.nowcoder.com/practice/fe6b651b66ae47d7acce78ffdd9a96c7
回溯,用set去重
# -*- coding:utf-8 -*- from collections import Counter class Solution: def Permutation(self, ss): # write code here arr = [c for c in ss] n = len(arr) if n <= 1: return [ss] res = set() hashMap = Counter(arr) # print("hashMap:", hashMap) def backtrack(arr, idx, track): if len(track) == len(arr): res.add(''.join(track)) return for i in range(0, len(arr)): # print("track:", track) # print("hashMap:", hashMap, "value:", hashMap.get(arr[i], 0)) if i == idx or hashMap.get(arr[i], 0) == 0: # print("bingo") continue track.append(arr[i]) hashMap[arr[i]] -= 1 backtrack(arr, i, track) track.pop() hashMap[arr[i]] += 1 return backtrack(arr, -1, []) return sorted(list(res))