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

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

NgRx in AG04

An Introduction to Adding Algolia Search to Your Gatsby Site

How to Reverse an Integer in JavaScript

We were asked what is the difference between Var, let and const and most of us said the difference…

Speech to text in the browser with the Web Speech API

Reduce Response Latency by Caching Preflight Requests

From Mocha to ES8 and Beyond

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
Newbie Developer

Newbie Developer

More from Medium

Nutritional Values

Poem: Thoughts Go Back.

Analyzing Soccer Statistics Across 3 Different Leagues

How To Learn Anything at 50+