---
# System prepended metadata

title: leetcode 46. Permutations
tags: [c++, leetcode]

---

# leetcode 46. Permutations

## permutation

```cpp
class Solution {
public:
    vector<vector<int>> res;
    void recur(vector<int> nums, vector<int> ans, int size){
        if(!size){
            res.push_back(ans);
            return;
        } 
        for(int i = 0; i < size; i++){
            vector<int> temp = ans;
            temp.push_back(nums[i]);
            vector<int> t = nums;
            t.erase(t.begin() + i);
            recur(t, temp, size - 1);
        }
    }
    vector<vector<int>> permute(vector<int>& nums) {
        vector<int> ans;
        recur(nums, ans, nums.size());
        return res;
    }
};
```

## swap
```cpp=
class Solution {
public:
    
    void recur(vector<int>& nums, vector<vector<int>>& res, int size){
        if(!size){
            res.push_back(nums);
            return;
        } 
        for(int i = 0; i < size; i++){
            swap(nums[i], nums[size - 1]);
            recur(nums, res, size - 1);
            swap(nums[i], nums[size - 1]);
        }
    }
    vector<vector<int>> permute(vector<int>& nums) {
        vector<vector<int>> res;
        recur(nums, res, nums.size());
        return res;
    }
};
```

###### tags: `leetcode` `c++`