304 North Cardinal St.
Dorchester Center, MA 02124

# Combinations LeetCode Solution

## Problem – Combinations

Given two integers `n` and `k`, return all possible combinations of `k` numbers chosen from the range `[1, n]`.

You may return the answer in any order.

Example 1:

``````Input: n = 4, k = 2
Output: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
Explanation: There are 4 choose 2 = 6 total combinations.
Note that combinations are unordered, i.e., [1,2] and [2,1] are considered to be the same combination.``````

Example 2:

``````Input: n = 1, k = 1
Output: []
Explanation: There is 1 choose 1 = 1 total combination.``````

Constraints:

• `1 <= n <= 20`
• `1 <= k <= n`

### Combinations LeetCode Solution in C++

``````class Solution {
public:
vector<vector<int>> combine(int n, int k) {
vector<vector<int>> result;
int i = 0;
vector<int> p(k, 0);
while (i >= 0) {
p[i]++;
if (p[i] > n) --i;
else if (i == k - 1) result.push_back(p);
else {
++i;
p[i] = p[i - 1];
}
}
return result;
}
};
``````

### Combinations LeetCode Solution in Java

``````    public static List<List<Integer>> combine(int n, int k) {
List<List<Integer>> combs = new ArrayList<List<Integer>>();
combine(combs, new ArrayList<Integer>(), 1, n, k);
return combs;
}
public static void combine(List<List<Integer>> combs, List<Integer> comb, int start, int n, int k) {
if(k==0) {
return;
}
for(int i=start;i<=n;i++) {
combine(combs, comb, i+1, n, k-1);
comb.remove(comb.size()-1);
}
}
``````

### Combinations LeetCode Solution in Python

``````from itertools import combinations

class Solution:
def combine(self, n, k):
return list(combinations(range(1, n+1), k))
``````
##### Combinations LeetCode Solution Review:

In our experience, we suggest you solve this Combinations LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the Combinations LeetCode Solution

Find on LeetCode

##### Conclusion:

I hope this Combinations LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

LeetCode Solutions

Hacker Rank Solutions

CodeChef Solutions