47. Permutations II (Medium)

Description:

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

Example:

Input: [1,1,2]
Output:
[
[1,1,2],
[1,2,1],
[2,1,1]
]


Solution:

class Solution:
    def permuteUnique(self, nums: List[int], sort = False) -> List[List[int]]:
        if len(nums) < 2:
            return [nums]
        
        if sort == False:
            nums.sort()
            
        result = []
        
        for i in range(len(nums)):
            if i > 0 and nums[i] == nums[i-1]:
                continue
            cache_start = [nums[i]]
            for cache_follow in self.permuteUnique(nums[:i]+nums[i+1:],True):
                result.append(cache_start + cache_follow)
                
        return result

Performance:

  • Runtime: 68 ms, faster than 94.08% of Python3 online submissions for Permutations II.
  • Memory Usage: 13.3 MB, less than 81.64% of Python3 online submissions for Permutations II.
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,452评论 0 10
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,959评论 0 23
  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 9,516评论 0 13
  • 从今晚开始为梦想开始熬夜啦!哈哈哈 倾尽全力! 半年之内我会很忙,可能无法顾及你的感受,希望你能理解。 一定要对俩...
    Ailsa_a73a阅读 79评论 0 1
  • 梁素红,焦点网络九期持续分享第153天(297)舞钢 今天提前写分享,接下来的几天,估计很繁忙。关注正向,我们只看...
    天高地阔心飞扬阅读 86评论 0 0