관리 메뉴

솜씨좋은장씨

[leetCode] 47. Permutations II (Python) 본문

Programming/코딩 1일 1문제

[leetCode] 47. Permutations II (Python)

솜씨좋은장씨 2020. 11. 17. 00:46
728x90
반응형

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

 

Example 1:

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

Example 2:

Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

 

Constraints:

  • 1 <= nums.length <= 8
  • -10 <= nums[i] <= 10

Solution

from itertools import permutations

class Solution:
    def permuteUnique(self, nums: List[int]) -> List[List[int]]:
        answer = []
        
        permus = list(permutations(nums, len(nums)))
        
        for permu in permus:
            if permu not in answer:
                answer.append(permu)
        
        return answer

먼저 Permutations를 활용해서 리스트를 만들어주고 그 중 유니크한 값들만 남겼습니다.

 

SOMJANG/CODINGTEST_PRACTICE

1일 1문제 since 2020.02.07. Contribute to SOMJANG/CODINGTEST_PRACTICE development by creating an account on GitHub.

github.com

Comments