-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0046-Permutations.cpp
More file actions
85 lines (74 loc) · 1.87 KB
/
0046-Permutations.cpp
File metadata and controls
85 lines (74 loc) · 1.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/*******************************************************************************
* 0046-Permutations.cpp
* Billy.Ljm
* 02 August 2023
*
* =======
* Problem
* =======
* https://leetcode.com/problems/permutations/
*
* Given an array nums of distinct integers, return all the possible
* permutations. You can return the answer in any order.
*
* ===========
* My Approach
* ===========
* Since we have to generate each possible permutation, we have no choice but to
* iterate through each of them. Luckily, C++ has an inbuilt function for
* iterating through permutations, which we'll use.
*
* This has a time complexity of O(n * n!), and a space complexity of O(n!),
* where n is the length of the array.
******************************************************************************/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
/**
* << operator for vectors
*/
template <typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
os << "[";
for (int i = 0; i < v.size(); i++) {
os << v[i] << ",";
}
os << "\b]";
return os;
}
/**
* Solution
*/
class Solution {
public:
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int>> out;
sort(nums.begin(), nums.end());
do {
out.push_back(vector<int>());
copy(nums.begin(), nums.end(), back_inserter(out.back()));
} while (next_permutation(nums.begin(), nums.end()));
return out;
}
};
/**
* Test cases
*/
int main(void) {
Solution sol;
vector<int> nums;
// test case 1
nums = { 1, 2, 3 };
std::cout << "permute(" << nums << ") = ";
std::cout << sol.permute(nums) << std::endl;
// test case 2
nums = { 0, 1 };
std::cout << "permute(" << nums << ") = ";
std::cout << sol.permute(nums) << std::endl;
// test case 3
nums = { 1 };
std::cout << "permute(" << nums << ") = ";
std::cout << sol.permute(nums) << std::endl;
return 0;
}