码迷,mamicode.com
首页 > 编程语言 > 详细

PYTHON算法时间空间复杂度节省TRICK

时间:2018-10-24 15:18:10      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:list   app   持续更新   ring   搜索   return   需要   trick   pytho   

节省时间复杂度:

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


持续更新

 

PYTHON算法时间空间复杂度节省TRICK

标签:list   app   持续更新   ring   搜索   return   需要   trick   pytho   

原文地址:https://www.cnblogs.com/phinza/p/9842525.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!