K- Combinations Algorithm

The K-Combinations Algorithm, also known as the K-Subsets Algorithm, is a method used to find all possible combinations of K elements within a larger set of N elements. This algorithm is a common problem-solving technique in combinatorial mathematics, computer science, and statistics. It is widely used in various applications, such as generating combinations for statistical analysis, sampling, and machine learning tasks. The algorithm can be implemented using recursive or iterative approaches, depending on the problem's requirements and specific constraints. The basic idea behind the K-Combinations Algorithm is to generate all possible subsets of the given set with exactly K elements. The algorithm starts by selecting the first element of the set and then recursively combines it with the remaining elements in the set. Once a combination of K elements is formed, the algorithm backtracks and moves to the next element in the set, repeating the process until all possible combinations are generated. One of the key aspects of this algorithm is that it eliminates duplicate combinations by ensuring that elements are selected in a specific order. The K-Combinations Algorithm is highly efficient and flexible, making it a popular choice for solving combinatorial problems in various domains.
/*
 Petar 'PetarV' Velickovic
 Algorithm: K-Combinations
*/

#include <stdio.h>
#include <math.h>
#include <string.h>
#include <iostream>
#include <vector>
#include <list>
#include <string>
#include <algorithm>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <complex>
using namespace std;
typedef long long lld;

int n, k;
int skup[100];
bool inSet[100];

//Program koji generise sve kombinacije od po K elemenata datog skupa
//Slozenost: O((n choose k))

void kCombinations(int pos, int amt)
{
    if (n-pos<k-amt) return;
    if (amt==k)
    {
        for (int i=0;i<n;i++) if (inSet[i]) printf("%d ",skup[i]);
        printf("\n");
        return;
    }
    inSet[pos] = true;
    kCombinations(pos+1,amt+1);
    inSet[pos] = false;
    kCombinations(pos+1,amt);
}

int main()
{
    n = 5, k = 2;
    skup[0] = 1;
    skup[1] = 2;
    skup[2] = 3;
    skup[3] = 4;
    skup[4] = 5;
    kCombinations(0, 0);
    return 0;
}

LANGUAGE:

DARK MODE: