Combinations

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

helper(1, [])
helper(2, [1])
helper(3, [1, 2])
helper(4, [1, 3])
helper(5, [1, 4])

helper(3, [2])
helper(4, [2, 3])
helper(5, [2, 4])

helper(4, [3])
helper(5, [3, 4])

helper(5, [4])
class Solution(object):
def combine(self, n, k):
self.ans = []
nums = [0 for _ in range(k)]
count = 0
self.backTrack(1, count, n, k, nums)
return self.ans


def backTrack(self, pos, count, n, k, nums):
if k==0:
self.ans.append(list(nums))
return
for i in range(pos, n-k+2):
nums[count] = i
count += 1
self.backTrack(i+1, count, n, k-1, nums)
count -= 1

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store