输入一个长度为 n 字符串,打印出该字符串中字符的所有排列,你可以以任意顺序返回这个字符串数组。
例如输入字符串ABC,则输出由字符A,B,C所能排列出来的所有字符串ABC,ACB,BAC,BCA,CBA和CAB。
数据范围:
要求:空间复杂度 ,时间复杂度
要求:空间复杂度 ,时间复杂度
输入一个字符串,长度不超过10,字符只包括大小写字母。
"ab"
["ab","ba"]
返回["ba","ab"]也是正确的
"aab"
["aab","aba","baa"]
"abc"
["abc","acb","bac","bca","cab","cba"]
""
[""]
# -*- coding:utf-8 -*- class Solution: def Permutation(self, ss): # write code here res = [] length = len(ss) visited = [False for _ in range(length)] path = [] def dfs(ss, length): if len(path) == length: temp = "".join(path) if temp not in res: res.append(temp) return None for i in range(length): if not visited[i]: path.append(ss[i]) visited[i] = True dfs(ss, length) path.pop() visited[i] = False dfs(ss, length) return res
# -*- coding:utf-8 -*- class Solution: def Permutation(self, ss): # write code here if not ss: return None if len(ss)==1&nbs***bsp;set(ss)==1: return [ss] res=[] for i in range(len(ss)): s1=ss[i] s2=ss[0:i]+ss[i+1:] for item in self.Permutation(s2): res.append(s1+item) res.append(item+s1) res=set(res) res=list(res) res=sorted(res) return res
# -*- coding:utf-8 -*- class Solution: def Allstring(self, ss): results = [] for i in range(len(ss)): temp1 = ss[i] temp2 = ss[:i] + ss[i + 1:] temp3 = self.Allstring(temp2) if temp3: for x in temp3: results.append(temp1 + x) else: results.append(temp1) return results def Permutation(self, ss): # write code here # get all string result = self.Allstring(ss) result = list(set(result)) result.sort() return result
# -*- coding:utf-8 -*- class Solution: def Permutation(self, ss): # write code here if len(ss) == 1: return [ss] if len(ss) == 2: return list(set([ss[::1], ss[::-1]])) temp = [[ss[0]]] for i in range(1, len(ss)): temp = self.getDefStr(temp, ss[i]) return sorted([''.join(i) for i in temp]) def getDefStr(self, temp, s): if not temp: temp.append(s) return temp res = [] for cur in temp: for i in range(len(cur) + 1): temp1 = cur[:] temp1.insert(i, s) if temp1 not in res: res.append(temp1) return res
# -*- coding:utf-8 -*- import itertools class Solution: def Permutation(self, ss): results = [] if ss == '': return results for i in itertools.permutations(ss, len(ss)): results.append(''.join([x for x in i])) results = list(set(results)) results.sort() return resultspython 直接可以用 itertools.permutations函数
# -*- coding:utf-8 -*- import copy class Solution: def Permutation(self, ss): if not ss: return [] def recu(str,tmtmp): for s in str: tmp = copy.copy(tmtmp) tmp = tmp+s strtmp = copy.copy(str) strtmp.remove(s) if(len(strtmp)==0): res.append(tmp) tmp = '' return recu(strtmp,tmp) ss = list(ss) tmp = '' res = [] recu(ss,tmp) return sorted(set(res))
class Solution: def Permutation(self, ss): if len(ss) <= 1: return ss if len(ss) <= 2: return sorted(list(set([ss,ss[1]+ss[0]]))) list_ = [] for i in range(len(ss)): first = ss[i] for i in self.Permutation(ss[:i]+ss[i+1:]): list_.append(first+i) return sorted(list(set(list_)))
# -*- coding:utf-8 -*- import itertools class Solution: def Permutation(self, ss): # write code here if not ss: return [] return sorted(list(set(map("".join, itertools.permutations(ss)))))
借鉴了动态规划的思想拆分出子问题,一个字符串'abc'
,可拆成'ab'
和'c'
,'ab'
本身有两种组合'ab'
和'ba'
,对于每一种组合'c'
有3个位置可以插。
同理对于长度为n的字符串,从第一个字符开始重复上述操作,递归到最后一个字符为止。
对于重复的问题可用set()
解决
# -*- coding:utf-8 -*- import copy class Solution: def Permutation(self, ss): # write code here # 边界情况 if ss == None: return if len(ss) == 1 or len(ss) == 0: return ss ss = list(ss) totalCombine = [ss[0]] for i in range(1, len(ss)): tmpCombine = [] s = ss[i] for cmb in totalCombine: # 将字符串打散成单个字母的list cmb = list(cmb) tmp = copy.deepcopy(cmb) # 新增字符插入n+1个不同位置 for j in range(len(cmb) + 1): cmb = copy.deepcopy(tmp) cmb.insert(j, str(s)) tmpCombine.append(''.join(cmb)) totalCombine = copy.deepcopy(tmpCombine) # 去重 totalCombine = sorted(list(set(totalCombine))) return totalCombine
# -*- coding:utf-8 -*- class Solution: def demo(self, s, rs, r): if len(s) == 1: rs += s[0] r.append(rs) return for i in range(len(s)): rs_t = rs + s[i] st = s[:] del st[i] self.demo(st[:], rs_t, r) def Permutation(self, ss): # write code here if not ss&nbs***bsp;len(ss) == 1: return ss rl = [] ss = list(ss) self.demo(ss[:], '', rl) rl = list(set(rl)) rl.sort() return rl
num ='abc' for i in num: for j in num: for m in num: if i!=j and i!=m and j!=m: print(i,j,m)
# -*- coding:utf-8 -*- class Solution: def Permutation(self, ss): # write code here strset = set() for c in ss: if not strset: strset.add(c) else: tmp_set = set() for item in strset: for i in range(len(item)+1): tmp = item[:i]+c+item[i:] tmp_set.add(tmp) strset = tmp_set
import copy class Solution: def Permutation(self, ss): if not ss: return [] elif len(ss) == 1: return ss else: ss = list(ss) arr1 = [ss] for k in range(len(ss), 1, -1): arr3 = [] for j in arr1: j = list(j) arr2 = self.se(j, k) for el in arr2: arr3.append(el) arr1 = copy.deepcopy(arr3) arr1 = list(set(arr1)) arr1.sort() return arr1 def se(self, ss, k): arr = [] st = ss[:k] sr = ss[k:] for k2 in range(len(st)-1, -1, -1): ss1 = self.swap(-1, st, k2) ss2 = ''.join(ss1) + ''.join(sr) arr.append(ss2) return arr def swap(self, k1, ss, k2): tt = copy.deepcopy(ss) tmp = tt[k2] tt[k2] = tt[k1] tt[k1] = tmp return tt
# -*- coding:utf-8 -*- class Solution: def __init__(self): self.result = list() def Permutation(self, ss): if len(ss) == 0: return [] ss_list = list() for s in ss: ss_list.append(s) self.Digui(ss_list, 0) self.resort(self.result) return self.result def Digui(self, ss, i): if i == len(ss) - 1: self.result.append("".join(ss)) return else: j = i while j < len(ss): if self.repeat(ss, i, j) == False: self.change(ss, i, j) self.Digui(ss, i + 1) self.change(ss, j, i) j += 1 def resort(self, ss): for i in range(0, len(ss)): for j in range(i, len(ss)): if ss[j] < ss[i]: self.change(ss, i, j) # write code here def change(self, ss, i, j): temp = ss[i] ss[i] = ss[j] ss[j] = temp def repeat(self, ss, i, j): while(i < j): if ss[i] == ss[j]: return True i += 1 return False
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中不同排列组合的一个string for j in self.Permutation(ss[:i]+ss[i+1:]): res.add(ss[i]+j) return sorted(res)
class Solution: def Permutation(self, ss): if len(ss) <= 1: return ss res=set() tmp=[] # 用一个dict记住每个单词出现次数 n_dict = dict((x,0) for x in ss) for s in ss: n_dict[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()
class Solution: def Permutation(self,ss): # write code here 回溯法 if len(ss)==0: return [] ss = list(ss) res = [] self.helper(ss,[],res) return res def helper(self,array,solution,res): if len(array)==0: s = "".join(solution) if s not in res: res.append(s) return for i in range (len(array)): newarray=array[:i]+array[i+1:]#删除第一个元素 newsolution=solution+[array[i]]#加入新元素 self.helper(newarray,newsolution,res)#寻找剩余元素的排列组合
# -*- coding:utf-8 -*- # 解题思路:递归法实现字符串全排列 # 第一步:使用交换法,第一位字符和每个字符交换 # 第二步:递归实现从第二位到最后的全排列 # 第三步:交换之后复位,进行下一位交换 # 边界条件: begin == end&nbs***bsp;begin == end - 1 # 使用set进行排查,使用sort函数按字典顺序排序 class Solution: def Permutation(self, ss): # write code here if ss == '': return [] ls = list(ss) start = 0 ln = len(ls) res = [] def permutation(lss, position, end): if position == end: res.append(''.join(lss)) for index in range(position, end): lss[position], lss[index] = lss[index], lss[position] permutation(lss, position + 1, end) lss[index], lss[position] = lss[position], lss[index] permutation(ls, start, ln) res = list(set(res)) res = sorted(res) return res
# -*- coding:utf-8 -*- class Solution: def Permutation(self, ss): if not ss: return [] #按字母顺序排序,为后面重复字符不重复计算做准备 l=list(ss) l.sort() ss=''.join(l) #dfs初始条件 visited=set() res=[] #采用深度优先遍历 def dfs(visited,ss,t): #结束条件 if len(t)==len(ss): res.append(t) return for i in range(len(ss)): if i in visited: continue #避免重复计算 if i-1>=0 and i-1 not in visited and ss[i]==ss[i-1]: continue visited.add(i) dfs(visited,ss,t+ss[i]) visited.remove(i) #运行dfs dfs(visited,ss,'') return res