
Sponsored
Sponsored
This approach uses recursion combined with backtracking to generate all possible permutations of the input array. The algorithm works by swapping elements of the array and recursively building permutations by fixing one element at a time until the entire array is permutated.
Time Complexity: O(n * n!) as there are n! permutations and we copy each permutation.
Space Complexity: O(n!) for storing the permutations, plus additional space used by the recursive stack.
1#include <vector>
2#include <algorithm>
3#include <iostream>
4
5std::vector<std::vector<int>> permute(std::vector<int>& nums) {
6 std::vector<std::vector<int>> result;
7 std::sort(nums.begin(), nums.end());
8 do {
9 result.push_back(nums);
10 } while (std::next_permutation(nums.begin(), nums.end()));
11 return result;
12}
13
14int main() {
15 std::vector<int> nums = {1, 2, 3};
16 std::vector<std::vector<int>> result = permute(nums);
17 for (const auto& permutation : result) {
18 for (int num : permutation) {
19 std::cout << num << " ";
20 }
21 std::cout << "\n";
22 }
23 return 0;
24}
25This C++ implementation uses the backtracking approach with the help of the std::next_permutation which efficiently generates lexicographical permutations using swaps. The result vector stores each permutation as they are generated.
An alternative iterative approach utilizes a queue to generate permutations level by level by inserting each number at every possible position within every possible permutation.
Time Complexity: O(n * n!), iterating through permutations.
Space Complexity: O(n!) for storing permutations, constant space for current permutation array.
1function
This JavaScript solution constructs permutations iteratively, finding and adjusting to the 'next lexicographical' permutation by manipulating indices and sublists within the array.