Home > Backend Development > C++ > How Can I Generate All k-Combinations of n Items in C ?

How Can I Generate All k-Combinations of n Items in C ?

Patricia Arquette
Release: 2024-11-21 01:06:14
Original
318 people have browsed it

How Can I Generate All k-Combinations of n Items in C  ?

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:

  • Each item is assigned a bit in the bitmask, with a set bit indicating that the item is included in the combination.
  • The algorithm iterates through all possible bitmask values, using the bitmask to determine which items are included in each combination.

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;
}
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template