Quick actions

cmd+k|ctrl+k

Navigation

Languages

permutations_shopdeck

Snippet info

Language

Cpp

Visibility

public

Author

parthbhadra14

Created

2023-12-06T14:17:46.869753Z

Updated

2023-12-06T14:17:46.869753Z

#include<iostream>
#include<vector>
#include<unordered_set>

using namespace std;

void print(vector<int> &A) {
    for(int i=0; i<A.size(); i++) {
        cout << A[i] << " ";
    }
    cout << endl;
}

string makeString(vector<int> &A) {
    string temp = "";
    for(int i=0; i<A.size(); i++) {
        temp += to_string(A[i]); // check this syntax 
    }
    return temp;
}



void generatePermutations(vector<int> &A) {
    unordered_set <string> set;
    int n = A.size();
    
    for(int i=0; i<n; i++) {
        for(int j=0; j<n; j++) {
            // make a string and check if it is already in the set
            if(i!=j) {
                swap(A[i], A[j]);
                string temp = makeString(A);
                if(set.find(temp) != set.end()) {
                    swap(A[i], A[j]);
                    continue;
                }
                set.insert(temp);
                
                print(A);
                swap(A[i], A[j]);
                
            } else {
                string temp = makeString(A); // 123
                if(set.find(temp) != set.end()) continue;
                set.insert(temp);
                print(A);
            }
            
        }
    }
    
    return;
    
    
}


void generatePermutations2(vector<int> &A, int idx, unordered_set<string> &set, string temp) {
    if(idx == A.size()) {
        print(A);
        set.insert(temp);

        return;
    }

    for(int i=0; i<A.size(); i++) {
        swap(A[i], A[idx]);
        string temp = makeString(A);
        if(set.find(temp) == set.end()) {
            generatePermutations2(A, idx+1, set, temp);
        }
        swap(A[i], A[idx]);
    }
}
int main() {

    vector<int> A = {1, 2, 3};
    unordered_set <string> set;

    generatePermutations2(A, 0, set, "");
    return 0;
}
INFO