Leetcode Combination Problem Solution

In this Leetcode Combination Problem Solution 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.

Leetcode Combination Problem Solution


Problem solution in Python.

class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
        def dfs(comb: List[int], i: int) -> None:
            if len(comb) == k:
                res.append(comb)
                return
            
            if i > n:
                return
            
            for i in range(i, n + 1):
                dfs(comb + [i], i + 1)
        
        res = []
        dfs([], 1)
        return res

Problem solution in Java.

import java.util.*;
class Main {
  public int findcomb(ArrayList <Integer>ar,int i,int n,int k)
  {
    if(ar.size()==k)
    {
      System.out.println(ar);
      return 1;
    }
    if(i==n+1)
      return 0;
    findcomb(ar,i+1,n,k);
    //ArrayList ar1=new ArrayList(ar);
    ar.add(i);
    findcomb(ar,i+1,n,k);
    ar.remove(ar.indexOf(i));
    return 0;
  }
  public static void main(String[] args) 
  {
    Main m=new Main();
    ArrayList <Integer>ar=new ArrayList<Integer>();
    m.findcomb(ar,1,5,3);
    //System.out.println("Hello world!");
  }
}


Problem solution in C++.

class Solution {
public:
void combination(vector<int>nums,vector<vector<int>>&ans, vector<int>
                &v, int l, int k)
{
    
    if(k == 0){
        
        ans.push_back(v);
        
        return ;
    }
    
    for(int i = l; i < nums.size( ); i++){
        
        v.push_back(nums[i]);  
        
        combination(nums,ans,v, i+1,k-1);
    
        v.pop_back( );
    }
 
}
vector<vector<int>> combine(int n, int k) {
    
    vector<vector<int>> ans;
    
    vector<int> v;
    
    vector<int> nums;
    
    int i;
    
    for(i = 1; i <= n; i++){
        
        nums.push_back(i);
 
    }
    combination(nums, ans, v, 0, k);
    
    return ans;
    
}
 
};


Problem solution in C.

int C(int n, int k){
    if(k > 1)
        return n * C(n - 1, k - 1) / k;
    else
        return n;
}
 
inline void create(int num, int n, int *ans){
    int i, j;
    for(i = 0, j = 0; i < n; i++){
        if((num & (1 << i)) > 0)
            ans[j++] = i + 1;
    }
}
 
int** combine(int n, int k, int* returnSize, int** returnColumnSizes){
    register int i, j, total = C(n, k), count = 0;
    int **ans = (int**)malloc(total * sizeof(int*));
    int *col = (int*)malloc(total * sizeof(int));
    for(i = 0; i < total; i++){
        ans[i] = (int*)calloc(k, sizeof(int));
        col[i] = k;
    }
    *returnColumnSizes = col;
    *returnSize = total;
    
    for(i = 1; i < 1 << n; i++){
        if(__builtin_popcount(i) == k){
            create(i, n, ans[count]);
            count++;
        }
    }
    
    return ans;
}


Post a Comment

0 Comments