zoukankan      html  css  js  c++  java
  • [LeetCode]题解(python):047-Permutations II


    题目来源


    https://leetcode.com/problems/permutations-ii/

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

    For example,
    [1,1,2] have the following unique permutations:
    [1,1,2][1,2,1], and [2,1,1].


    题意分析
    Input:list

    Output:permutations

    Conditions:跟上题类似,但是会有重复的元素


    题目思路


    直接用上题的做法,首先先排序,然后再遍历的时候用一个pre记录先前位置,如果当前位置与pre相同则跳过


    AC代码(Python)


     1 class Solution(object):
     2     def permuteUnique(self, nums):
     3         """
     4         :type nums: List[int]
     5         :rtype: List[List[int]]
     6         """
     7         nums.sort()
     8         if len(nums) == 1:
     9             return [nums]
    10         res = []
    11         pre = None
    12         for i in range(len(nums)):
    13             if nums[i] == pre:
    14                 continue
    15             pre = nums[i]
    16             for j in self.permuteUnique(nums[:i] + nums[i+1:]):
    17                 res.append([nums[i]] + j)
    18         return res
  • 相关阅读:
    Mysql 配置主从
    ZJ 虚拟机扩直接扩原磁盘
    Linux 配置samba
    mysql 5.6 升级5.7
    binlog作用
    删除全部binlog不影响数据库运行,类似Oracle的archivelog
    mysql清理binlog
    Perl计数器
    perl增量分析日志
    perl 获取更新部分日志
  • 原文地址:https://www.cnblogs.com/loadofleaf/p/5088266.html
Copyright © 2011-2022 走看看