Advertisement
Fastrail08

Permutations (n P r)

Jun 2nd, 2025
646
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.11 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. void getAllPerm(int item, int &r, vector<int> &boxes, int &count){
  5.    
  6.     // explore all the options/choose box for the current item
  7.     /*
  8.     n = 5, r = 3, item = 1
  9.    
  10.     _ _ _ _ _ (5 empty boxes present for item 1)
  11.    
  12.     So item 1 could explore/choose any of the box
  13.    
  14.     1 _ _ _ _ , _ 1 _ _ _ , _ _ 1 _ _ , _ _ _ 1 _ , _ _ _ _ 1 [explore all these paths]
  15.    
  16.     Now at next level, we will make decision for item item 2
  17.    
  18.     If we are currently exploring the path where 1 _ _ _ _,
  19.    
  20.     So 2 would have 4 options as there are 4 different empty boxes where 2 could go
  21.    
  22.     1 2 _ _ _ , 1 _ 2 _ _ , 1 _ _ 2 _ , 1 _ _ _ 2
  23.    
  24.     Repeat the same for the all the items available i.e. r
  25.    
  26.     This would generate all the perm, for example while exploring branch where _ 1 _ _ _ and currently at level 2
  27.    
  28.     The 4 options would be -
  29.    
  30.     2 1 _ _ _ , _ 1 2 _ _ , _ 1 _ 2 _ , _ 1 _ _ 2
  31.    
  32.     The first option is a permutation of 1 2 _ _ _    [2 & 1 arranged themselves]
  33.    
  34.     */
  35.    
  36.     //base case
  37.     if(item > r){
  38.         // item > r; as when we would have made the decision/explored options for the last item, say 3, we would have called to 4
  39.         count++;
  40.         for(int i : boxes){
  41.             cout << i;
  42.         }
  43.         cout << '\n';
  44.         return;
  45.     }
  46.    
  47.     for(int i = 0; i < boxes.size(); i++){
  48.         // only choose those boxes which are empty because that's where the current item could go
  49.         if(boxes[i] == 0){
  50.             //place the item in the box such as to start generating perm like (1 _ _ _ _ ....)
  51.             boxes[i] = item;
  52.             // call the next level
  53.             getAllPerm(item + 1, r, boxes, count);
  54.             // backtrack the current option at the current state and choose other options as (_ 1 _ _ _ , _ _ 1 _ _ ...)
  55.             boxes[i] = 0;
  56.         }
  57.     }
  58. }
  59.  
  60. int main() {
  61.     // your code goes here
  62.     int n, r;
  63.     cin >> n >> r;
  64.     vector<int> boxes(n, 0);
  65.     int count = 0;
  66.     getAllPerm(1, r, boxes, count);
  67.     cout << count << '\n';
  68. }
  69.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement