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

How To Set Up a React Project with Create React App

Reactions

How to setup CI/CD workflow for Node.js apps with Jenkins and Kubernetes

How to use CSS grid layout including a react example

Creating an SVG based Charting library from scratch

How to use nested loop in HTML and JavaScript

Class 8 — -204

All I wanted to do is scrape in JavaScript…

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

Geographies of Solitude wins Best Canadian Experimental Documentary!

Facing The Enemy by Paige Edwards

Debit card entry flow

TryHackme — Hamlet