A simple but time consuming python sloution


  • 2
    import random
    import math
    class Solution(object):
        def permute(self, nums):
            num=nums[:]
            tem=num[:]
            res=[num]
            length=len(res)
            while(len(res)<math.factorial (len(nums))):
                if(tem not in res):
                    res.append(tem)
                else:
                    random.shuffle(nums)
                    tem=nums[:]
            return res
            
        
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """

  • 2

    Just a shorter version...

    def permute(self, nums):
        res = []
        while len(res) < math.factorial(len(nums)):
            while nums in res:
                random.shuffle(nums)
            res.append(nums[:])
        return res
    

    Or:

    def permute(self, nums):
        res = []
        while len(res) < math.factorial(len(nums)):
            random.shuffle(nums)
            if nums not in res:
                res.append(nums[:])
        return res

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.