[LeetCode] 46. Permutations - 파이썬(Python)

2022. 5. 12. 14:29·Solving Algorithm Problem/LeetCode

문제 링크 : https://leetcode.com/problems/permutations/

 

Permutations - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

유형 : 백트래킹(BackTracking)

문제 설명

중복되지 않는 정수들이 담긴 배열 nums가 주어질 때, 만들 수 있는 모든 순열을 return하는 문제이다. 임의의 순서로 return하면 된다.

Example 1)
Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Example 2)
Input: nums = [0,1]
Output: [[0,1],[1,0]]
Example 3)
Input: nums = [1]
Output: [[1]]

제한사항

  • 1 <= nums.length <= 6
  • -10 <= nums[i] <= 10
  • nums의 모든 숫자들은 unique하다.

문제 풀이

성공 코드

from typing import List

class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        self.nums = nums
        self.perms = []
        
        self.bt([])
        return self.perms
    
    def bt(self, crnt_set: List[int]):
        if len(crnt_set) == len(self.nums):
            self.perms.append(crnt_set.copy())
            return
        
        for num in self.nums:
            if num in crnt_set:
                continue
            
            crnt_set.append(num)
            self.bt(crnt_set)
            crnt_set.pop()

시간복잡도 : n*n! <= T(n) <= n^2*n!

공간복잡도 : O(n)

저작자표시
'Solving Algorithm Problem/LeetCode' 카테고리의 다른 글
  • [LeetCode] 39. Combination Sum - 파이썬(Python)
  • [LeetCode] 77. Combinations - 파이썬(Python)
  • [LeetCode] 78. Subsets - 파이썬(Python)
  • [LeetCode] 17. Letter Combinations of a Phone Number - 파이썬(Python)
김행만
김행만
이모저모 다 적기
  • 김행만
    hyeinisfree
    김행만
  • 전체
    오늘
    어제
    • 분류 전체보기 (41)
      • AWS (0)
      • Network (6)
      • CICD (1)
      • Spring (0)
      • Ruby on Rails (0)
      • Java (12)
      • Python (1)
      • Computer Science (6)
        • Algorithm (2)
        • Data Structure (3)
        • Database (0)
        • Design Pattern (1)
      • Solving Algorithm Problem (12)
        • LeetCode (12)
        • Programmers (0)
      • 자격증 (1)
      • Tip (1)
      • Etc (1)
        • 도서, 강의 (1)
        • Talk (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

    • GitHub
  • 공지사항

  • 인기 글

  • 태그

    java
    CISCO
    java 필수 문법
    Network
    Packet Tracer
    cisco packet tracer
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
김행만
[LeetCode] 46. Permutations - 파이썬(Python)
상단으로

티스토리툴바