Combinations Algorithm

The Combinations Algorithm, also known as the binomial coefficient, is a fundamental concept in combinatorics, which deals with the various ways to combine elements of a finite set. It is often utilized in probability theory, statistics, and various branches of mathematics to solve problems involving arrangements, selections, and permutations. The algorithm calculates the number of possible combinations of a set of 'n' elements taken 'k' at a time, without repetition and where the order of elements does not matter. It is denoted by C(n, k) or C(n, k) = n! / (k!(n-k)!), where '!' represents the factorial function. The Combinations Algorithm has numerous real-world applications, such as in determining the combinations of a hand in card games like poker, predicting the number of possible genetic variations in biology, and even in analyzing social networks to find the number of possible connections between users. The algorithm is also a core component of the Pascal's Triangle, a triangular array of numbers where each number is the sum of the two numbers directly above it, representing the coefficients of binomial expansions. By understanding and implementing the Combinations Algorithm, one can effectively solve complex problems involving combinations and arrangements, allowing for deeper insights and more accurate predictions in various fields of study.
class Solution {
public:
    vector<vector<int> > combine(int n, int k) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        vector<vector<int>> result;
        vector<int> comb;
        DFS(comb, 0, 0, k, n, result);
        return move(result);
    }
    
    void DFS(vector<int>& comb, int step, int p, int k, int n, vector<vector<int>>& result) {
        if (step == k) {
            result.push_back(comb);
            return;
        }
        if (n - p < k - step) 
            return;
        
        comb.push_back(p + 1);
        DFS(comb, step + 1, p + 1, k, n, result);
        comb.pop_back();
        
        DFS(comb, step, p + 1, k, n, result);
    }
};

LANGUAGE:

DARK MODE: