Combinations (Leetcode 77)
Hint: Similar to subsets problem (Use Choose or don't choose method)
Problem Link: https://leetcode.com/problems/combinations/
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
ans=[]
def recursion(i,n,tempAns,k):
# If the number of remaining spaces for the combination
# is greater than available integers, we cannot get
# a combination of k size.
if(k-len(tempAns)>n-i+1):
return
# If we have reached size k for a combination,
# store the combination in ans and return from there.
if(len(tempAns)==k):
ans.append(tempAns)
return
temp=tempAns[:]
temp.append(i)
recursion(i+1,n,tempAns,k)
recursion(i+1,n,temp,k)
recursion(1,n,[],k)
return ans
Last updated