Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

permute #3

Open
Printkaran opened this issue Jul 13, 2023 · 0 comments
Open

permute #3

Printkaran opened this issue Jul 13, 2023 · 0 comments

Comments

@Printkaran
Copy link

#include

using namespace std;

void swap(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}

void generatePermutations(int* nums, bool* used, int* perm, int size, int index, bool allowRepetition) {
if (index == size) {
for (int i = 0; i < size; i++) {
cout << perm[i] << " ";
}
cout << endl;
return;
}

for (int i = 0; i < size; i++) {
    if (!allowRepetition && i > 0 && nums[i] == nums[i - 1] && !used[i - 1])
        continue;

    if (!used[i]) {
        used[i] = true;
        perm[index] = nums[i];
        generatePermutations(nums, used, perm, size, index + 1, allowRepetition);
        used[i] = false;
    }
}

}

void permute(int* nums, int size, bool allowRepetition) {
bool* used = new bool[size];
int* perm = new int[size];

for (int i = 0; i < size; i++)
    used[i] = false;

generatePermutations(nums, used, perm, size, 0, allowRepetition);

delete[] used;
delete[] perm;

}

int main() {
int size;
cout << "Enter the number of elements: ";
cin >> size;

int* nums = new int[size];
cout << "Enter the elements: ";
for (int i = 0; i < size; i++) {
    cin >> nums[i];
}

bool allowRepetition;
cout << "Allow repetition? (1 for yes, 0 for no): ";
cin >> allowRepetition;

permute(nums, size, allowRepetition);

delete[] nums;

    return 0;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant