Created
February 3, 2019 05:59
-
-
Save DrynnBavis/1e55965d745c1bcafe746261b390b1f3 to your computer and use it in GitHub Desktop.
C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Solution { | |
| private: | |
| int fact(int n) { | |
| int ans = 1; | |
| for(int i = 1; i <= n; ++i) ans *= i; | |
| return ans; | |
| } | |
| public: | |
| vector<vector<int>> permute(vector<int>& nums) { | |
| const int n = nums.size(); | |
| vector<vector<int>> ans; | |
| ans.reserve(fact(n)); | |
| function<void(vector<int>&,int)> permutation = | |
| [&ans, n, &permutation](vector<int>& nums, int k) { | |
| if(k == n - 1) ans.push_back(nums); | |
| for(int i = k; i < n; ++i) { | |
| swap(nums[k], nums[i]); | |
| permutation(nums, k+1); | |
| swap(nums[k], nums[i]); | |
| } | |
| }; | |
| permutation(nums, 0); | |
| return ans; | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment