Combinations of Items in C
Introduction
Generating all possible combinations of items is a common challenge in many applications. This article explores an efficient algorithm for generating all k-combinations of n items in C .
The Algorithm
The algorithm employs a bitmask technique to represent the combinations:
Code Implementation
#include <iostream> #include <vector> using namespace std; void combinations(vector<int>& items, int k) { int n = items.size(); for (int bitmask = 0; bitmask < (1 << n); bitmask++) { vector<int> combination; for (int i = 0; i < n; i++) { if ((bitmask >> i) & 1) { combination.push_back(items[i]); } } cout << "Combination: "; for (int item : combination) { cout << item << " "; } cout << endl; } } int main() { vector<int> items = {1, 2, 3, 4, 5}; int k = 3; combinations(items, k); return 0; }
Output
Combination: 1 2 3 Combination: 1 2 4 Combination: 1 2 5 Combination: 1 3 4 Combination: 1 3 5 Combination: 1 4 5 Combination: 2 3 4 Combination: 2 3 5 Combination: 2 4 5 Combination: 3 4 5
Analysis
The algorithm's complexity is O(n * 2^n), where n is the number of items. This is because it iterates through all possible bitmask values, each of which represents a unique combination.
The above is the detailed content of How Can I Generate All k-Combinations of n Items in C ?. For more information, please follow other related articles on the PHP Chinese website!