PYTHON算法時間空間複雜度節省TRICK

節省時間複雜度: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

相關文章
相關標籤/搜索