Advertisement
Fastrail08

Partition in K subsets

May 4th, 2025
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.15 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. void printKPartition(int level, int n, int k, vector<vector<int> > v){
  5.     //answer valid only when k = 0 & level > n
  6.     if(level > n){
  7.         if(k == 0){
  8.             for(vector<int> i : v){
  9.                 cout << "[";
  10.                 for(int j : i){
  11.                     cout << ' ' << j;
  12.                 }
  13.                 cout << ']';
  14.             }
  15.             cout << '\n';
  16.         }
  17.         return;
  18.     }
  19.     //can create a different partition
  20.     if(k != 0){
  21.         vector<int> partition;
  22.         partition.push_back(level);
  23.         v.push_back(partition);
  24.         printKPartition(level + 1, n, k - 1, v);    
  25.         v.pop_back();
  26.     }
  27.    
  28.     //don't create a separate partition, go in existing ones
  29.     //NOTE - if there is no existing subset, don't call
  30.     if(v.size() != 0){
  31.         for(int i = 0; i < v.size(); i++){
  32.             v[i].push_back(level);
  33.             printKPartition(level + 1, n, k, v);
  34.             v[i].pop_back();
  35.         }
  36.     }
  37. }
  38.  
  39. int main() {
  40.     // your code goes here
  41.     int n, k;
  42.     cin >> n >> k;
  43.     vector<vector<int> > v;
  44.     printKPartition(1, n , k, v);
  45.  
  46. }
  47.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement