节省时间复杂度:

sorted + 跳过重复目标 +记忆搜索

例子:字符串的不同排列

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


持续更新