Here's a C++ code to find all permutations of an array using recursion:
#include <iostream>
#include <vector>
using namespace std;
void swap(vector<int>& arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
void permutations(vector<int>& arr, int start, int end) {
if (start == end) {
// Base case: We have reached the end of the array
// Print the current permutation
for (int i = 0; i <= end; i++) {
cout << arr[i] << " ";
}
cout << endl;
} else {
// Recursive case: Swap each element with the start element
// and recursively generate permutations for the remaining elements
for (int i = start; i <= end; i++) {
swap(arr, start, i);
permutations(arr, start + 1, end);
swap(arr, start, i); // Backtrack: Undo the swap
}
}
}
int main() {
vector<int> arr = {1, 2, 3};
int n = arr.size();
cout << "Permutations of the array:" << endl;
permutations(arr, 0, n - 1);
return 0;
}
Output:
Permutations of the array:
1 2 3
1 3 2
2 1 3
2 3 1
3 2 1
3 1 2
Explanation:
The code utilizes recursion to generate permutations by systematically swapping elements and exploring all possible combinations. The base case ensures that the recursion stops when the end of the array is reached, and the permutations are printed. The recursive case generates permutations for the remaining elements by swapping the current element with each subsequent element and recursively generating permutations for the rest. Backtracking is performed to restore the array to its original state after each iteration.
153 videos|115 docs|24 tests
|
|
Explore Courses for Software Development exam
|