题解 | #字符串的排列#

字符串的排列

https://www.nowcoder.com/practice/fe6b651b66ae47d7acce78ffdd9a96c7

import copy
class Solution:
    def Permutation(self , str: str) -> list[str]:
        # write code here
        self.str_len = len(str)
        self.cand = []
        self._build('', str, 0)        
        return self.cand
    
    def _build(self, prefix, rem_str, length):
        if length == self.str_len:
            self.cand.append(prefix)
        vis = set()
        for i, ele in enumerate(rem_str):
            if ele in vis:
                continue
            else:
                vis.add(ele)
            self._build(prefix+ele, rem_str[:i]+rem_str[i+1:], length+1)

关键在于有重复元素的处理,原先我建立了hash字典,但是这样的字典在每一次递归时都会copy一次,超时。所以用了集合表示当前递归已经用过的元素。

所以尽量不要deepcopy

全部评论

相关推荐

04-28 22:33
已编辑
门头沟学院 C++
点赞 评论 收藏
分享
mjasjon:这种trash中厂 简历过筛概率比大厂还低(除阿里系)
投递哔哩哔哩等公司7个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务