节省时间复杂度:app
sorted + 跳太重复目标 +记忆搜索spa
例子:字符串的不一样排列内存
import copy
class Solution:
def stringPermutation2(self, str):
str = ''.join(sorted(str)) #部分版本的PY好像str只能以这种方式进行sorted
return self.helper(str, {})
def helper(self, head, memory):
if len(head) < 2:
return [head]
if head in memory:
return memory[head] #动用记忆,若是目标出现过,直接return对应记忆
result = []
for i in range(len(head)):
if i != 0 and head[i] == head[i-1]: #跳太重复目标
continue
if len(head) == 2:
return [head[i] + head[i+1], head[i+1] + head[i]]
sub = self.helper(head[:i] + head[i + 1:], memory)
for j in sub:
result.append(head[i] + j)
result = list(set(result)) #将result去重是为了尽量节省memory即将动用的内存/另外result也确实须要去重
memory[head] = result #动用记忆,将其储存
return result字符串
持续更新string