[Leetcode] 77. Combinations

2022. 12. 2. 23:58·코딩테스트/Python
728x90
반응형

🔗 Problem Link

 

Combinations - 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


❔Thinking

  • 1부터 n까지의 숫자들 가운데 k개를 뽑아 조합한 결과를 반환한다.

💻Solution

1. 조합을 활용한 풀이

from itertools import combinations
def combine(self, n: int, k: int):
    n_list = [i for i in range(1,n+1)]
    return list(combinations(n_list, k))

 

2. DFS을 활용한 풀이

def combine(self, n: int, k: int):
    nums = [i for i in range(1, n+1)]
    result = []
    stack = [[0, nums, []]]
    while stack:
        length, integers, ans = stack.pop()
        if length == k:
            result.append(ans)
        else:
            for i in range(len(integers)):
                stack.append([length+1, integers[i+1:], ans+[integers[i]]])
    return result

🗝️keypoint

  1. DFS를 활용할 때, [1,2] 와 [2,1]를 하나로 합치기 위한 sort나 set()은 시간초과가 발생한다.
저작자표시 (새창열림)

'코딩테스트 > Python' 카테고리의 다른 글

[Baekjoon] 18352. 특정 거리의 도시 찾기  (0) 2022.12.29
[Programmers] Level 2. 두 큐 합 같게 만들기  (1) 2022.12.26
[Leetcode] 46. Permutations  (0) 2022.12.02
[Leetcode] 17. Letter Combinations of a Phone Number  (0) 2022.12.02
[Leetcode] 200. Number of Islands  (0) 2022.12.01
'코딩테스트/Python' 카테고리의 다른 글
  • [Baekjoon] 18352. 특정 거리의 도시 찾기
  • [Programmers] Level 2. 두 큐 합 같게 만들기
  • [Leetcode] 46. Permutations
  • [Leetcode] 17. Letter Combinations of a Phone Number
swwho
swwho
일상을 데이터화하다
  • swwho
    하루한장
    swwho
  • 전체
    오늘
    어제
    • 분류 전체보기 (188)
      • ML_DL (39)
        • MUJAKJUNG (무작정 시리즈) (18)
        • 딥러닝 공부하기 (21)
      • 데이터사이언스 (1)
        • EDA (1)
        • 데이터과학을 위한 통계 (0)
      • 데이터엔지니어링 (2)
      • 논문리뷰 (2)
        • Computer Vision (2)
      • Python 활용하기 (12)
      • 코딩테스트 (127)
        • Python (109)
        • MySQL (14)
      • Git (3)
      • MySQL 활용하기 (0)
      • 일상 이야기 (1)
  • 블로그 메뉴

    • 홈
    • 태그
  • 최근 글

  • 250x250
  • hELLO· Designed By정상우.v4.10.3
swwho
[Leetcode] 77. Combinations
상단으로

티스토리툴바