zoukankan      html  css  js  c++  java
  • Permutations and Permutations II

    Permutations

    问题:给定一个无重复元素的数组,输出其中元素可能的所有排列

    示例:

      输入:[2,3,4]

      输出:[

        [2,3,4],

        [2,4,3],

        [3,2,4],

        [3,4,2],

        [4,2,3],

        [4,3,2]

      ]

    解决思路:循环加递归

    class Solution(object):
        def permute(self, nums):
            """
            :type nums: List[int]
            :rtype: List[List[int]]
            """
            self.out = []
            self.per(nums)
            return self.out
        
        def per(self,nums,one_per=[]):
            if not nums:
                self.out.append(one_per)
                return
            for i in nums:
                remain = nums[:]
                remain.remove(i)
                self.per(remain,one_per+[i])

    Permutations II

    问题:给定一个可能带有重复元素的数组,输出其元素可能的所有排列,不能重复输出

    示例:

      输入:[1,2,1]

      输出:[

        [1,1,2],

        [1,2,1],

        [2,1,1]

        ]

    Python代码:

    class Solution(object):
        def permuteUnique(self, nums):
            """
            :type nums: List[int]
            :rtype: List[List[int]]
            """
            self.out = []
            nums.sort()
            self.per(nums)
            return self.out
            
        def per(self,nums,one_per=[]):
            if not nums:
                self.out.append(one_per)
                return
            for i in range(len(nums)):
                if i > 0 and nums[i] == nums[i-1]:
                    continue
                self.per(nums[:i]+nums[i+1:],one_per+[nums[i]])
  • 相关阅读:
    外观模式
    享元模式
    c#中的抽象类和接口
    装饰者模式
    组合模式
    适配器模式
    springboot 源码篇002## web层自动装配部分源码
    springboot 源码篇002## 自动装配原理
    springboot 源码篇 01
    shell 脚本基础 第二篇
  • 原文地址:https://www.cnblogs.com/wenqinchao/p/10847949.html
Copyright © 2011-2022 走看看