Combinations - LeetCode

 

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

 

그냥 combination 구현하는 문제다.

 

class Solution:
    
    def helper(self, n, k, comb, result):
        if len(comb) == k:
            result.append(comb[:])
            return
        
        if n == 0:
            return
        
        for i in range(n, 0, -1):
            self.helper(i - 1, k, comb + [i], result)
    
    def combine(self, n: int, k: int) -> List[List[int]]:
        result = []
        self.helper(n, k, [], result)
        return result

 

다른 사람 풀이도 봐볼까

 

class Solution(object):
    def combine(self, n, k):
        ret = []
        self.dfs(list(range(1, n+1)), k, [], ret)
        return ret
    
    def dfs(self, nums, k, path, ret):
        if len(path) == k:
            ret.append(path)
            return 
        for i in range(len(nums)):
            self.dfs(nums[i+1:], k, path+[nums[i]], ret)

비슷하넹

+ Recent posts