Combinations LeetCode Solution

Last updated on October 10th, 2024 at 12:07 am

Here, We see Combinations LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.

List of all LeetCode Solution

Topics

Backtracking

Level of Question

Medium

Combinations LeetCode Solution

Combinations LeetCode Solution

Problem Statement

Given two integers n and k, return all possible combinations of k numbers are 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: [[1]]
Explanation: There is 1 choose 1 = 1 total combination.

1. Combinations Leetcode Solution C++

class Solution {
public:
    vector<vector<int>> combine(int n, int k) {
        vector<int> temp;
        vector<vector<int>> ans;
        
        help(1, temp, ans, n, k);
        return ans;
    }
    
    void help(int num, vector<int> &temp, vector<vector<int>> &ans, int n, int k){
        if(temp.size() == k){
            ans.push_back(temp);
            return;
        }
        for(int i=num; i<=n; i++){
            temp.push_back(i);
            help(i+1, temp, ans, n, k);
            temp.pop_back();   
        }        
    }
};

2. Combinations Leetcode Solution Java

class Solution {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        if (k > n || k < 0) {
            return result;
        }
        if (k == 0) {
            result.add(new ArrayList<Integer>());
            return result;
        }
        result = combine(n - 1, k - 1);
        for (List<Integer> list : result) {
            list.add(n);
        }
        result.addAll(combine(n - 1, k));
        return result;
    }
}

3. Combinations Leetcode Solution JavaScript

var combine = function(n, k) {
    if (n == 1 && k == 1) return [[1]];
    let out = [];
    const dfs = (currentSolution, startNumber, out) => {
        if (currentSolution.length == k) out.push(Array.from(currentSolution));
        for (let i = startNumber; i <= n; i++) {
            currentSolution.push(i);
            dfs(currentSolution, i + 1, out);
            currentSolution.pop();
        }
    }
    dfs([], 1, out);
    return out;
};

4. Combinations Leetcode Solution Python

class Solution(object):
    def combine(self, n, k):
        if k == 0:
            return [[]]
        return [pre + [i] for i in range(k, n+1) for pre in self.combine(i-1, k-1)]
Scroll to Top