Scribbling

LeetCode: 46. Permutations 본문

Computer Science/Coding Test

LeetCode: 46. Permutations

focalpoint 2021. 9. 7. 21:30

DFS Solution.

from itertools import permutations

class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        # Using Library
        # return list(permutations(nums, len(nums)))
        ret = []
        self.helper(nums, [], ret)
        return ret
        
    def helper(self, nums, element, ret):
        if not nums:
            ret.append(element)
        for i, num in enumerate(nums):
            self.helper(nums[:i]+nums[i+1:], element+[num], ret)


A lazy solution using generator.

class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        self.ret = []
        for out in self.gen(nums):
            self.ret.append(out)
        return self.ret
        
    def gen(self, nums):
        if not nums:
            yield []
        
        for i, num in enumerate(nums):
            for out in self.gen(nums[:i]+nums[i+1:]):
                yield [num] + out

'Computer Science > Coding Test' 카테고리의 다른 글

LeetCode: 41. First Missing Positive  (0) 2021.09.08
LeetCode: 47. Permutations II  (0) 2021.09.07
LeetCode: 40. Combination Sum II  (0) 2021.09.07
37. Sudoku Solver  (0) 2021.09.06
36. Valid Sudoku  (0) 2021.09.06