Given an array nums of distinct integers. Return all the possible permutations. You can return the answer in any order.

PHOTO EMBED

Wed Feb 12 2025 06:25:36 GMT+0000 (Coordinated Universal Time)

Saved by @Rohan@99

#include <iostream>
#include <vector>
using namespace std;

void HeapPermutation(vector<int>& nums, int size)
{
    if (size == 1) 
    {
        for (int num : nums)
            cout << num << " ";
        cout << endl;
        
        return;
    }

    for (int i = 0; i < size; i++) {
        HeapPermutation(nums, size - 1);

        if (size % 2 == 1) 
            swap(nums[0], nums[size - 1]);
        else 
            swap(nums[i], nums[size - 1]);
    }
}

int main() {
    int n;
    cin >> n;
    
    vector<int> nums(n);
    for (int i = 0; i < n; i++)
        cin >> nums[i];

    HeapPermutation(nums, n);

    return 0;
}
content_copyCOPY