Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

Example:

Input: n = 4, k = 2 Output: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]

My code:

class Solution:
    def combine(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: List[List[int]]
        """
        if n==0:
            return []
        if k==0:
            return [[]]
        start=1
        lists=self.Combine(start,n,k)
        return lists
    def Combine(self,start,n,k):
        if k==1:
            lists=[]
            for m in range(start,n+1):
                lists.append([m])
            return lists
        lists=[]
        for m in range(start,n+1):
            tmp_list=self.Combine(m+1,n,k-1)
            for item in tmp_list:
                item=[m]+item
                lists.append(item)
        return lists
        

Solution: https://leetcode.com/problems/combinations/