# Combinations

## Problem

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

You may return the answer in **any order**.

{% hint style="info" %}
For example:

```
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]]
```

{% endhint %}

### Thought Process

![](/files/-MNJYy8nCJRg46RCv5Tp)

* The for-loops and recursion method are very similar to the Subset problem, apart from the part that stops the DFS/recursion; for this problem it's when k = 0.

* We can generate the subsets in pairs of  *k*  by decreasing *k* inside the recursion method. This is basically like saying "Hey we have 1 number (which is that specific number the for loop is on) so we can explore the other numbers in our recurrsion and while doing so, we'll decrease k."

## Solution

```
class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
        soln = [] 
        self.helper(n,k,1,soln,[])
        return soln
    
    def helper(self, n, k, index, soln, subset):
        
        if k == 0:
            soln.append(list(subset))
        
        for i in range(index, n+1):
            subset.append(i)
            self.helper(n, k-1, i+1, soln, subset)
            subset.pop()
```

## Key Points

* The for-loop is the important factor that helps us traverse the "branches" for each number.

* We are decreasing *k* in our recursion method which helps us keep track of how many numbers we can append to the subset list still.

## Time Complexity

![](/files/-MNJbwalDPUHLismsk9I)

* **Time:** $$O((N!/(N-k)! \* k!) \* k)$$ because of the combination formula and we multiply that by k because of our operation of copying the list in k time (since there is only k elements in the combination list)

* **Space:** $$O(N-k)$$ because this will be the max depth of the  recursion call stack


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://joshualbarb.gitbook.io/leetcode-problems/backtracking/combinations.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
