Skip to content

Instantly share code, notes, and snippets.

@DrynnBavis
Created February 3, 2019 05:59
Show Gist options
  • Select an option

  • Save DrynnBavis/1e55965d745c1bcafe746261b390b1f3 to your computer and use it in GitHub Desktop.

Select an option

Save DrynnBavis/1e55965d745c1bcafe746261b390b1f3 to your computer and use it in GitHub Desktop.
C++
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