zoukankan      html  css  js  c++  java
  • PYTHON算法时间空间复杂度节省TRICK

    节省时间复杂度:

    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


    持续更新

     

  • 相关阅读:
    group by;having;order by
    oracle官方文档
    oracle正则表达式函数和正则表达式简介
    oracle系统函数
    oracle系统表
    windows搭建ftp服务器
    开机自动挂载
    linux修改设置ip地址
    My First Web Server
    为什么要写博客?
  • 原文地址:https://www.cnblogs.com/phinza/p/9842525.html
Copyright © 2011-2022 走看看