Description
![](https://kickstart.best/wp-content/uploads/2020/08/image-5-1024x653.png)
Submission
class Solution { public: vector<vector<int>> permute(vector<int>& nums) { vector<bool> used(nums.size(), false); vector<vector<int>> res; backtrack(used, nums, res, {}, 0); return res; } private: void backtrack(vector<bool>& used, vector<int>& nums, vector<vector<int>>& res, vector<int> hand, int used_count) { if(used_count == nums.size()) { res.push_back(hand); return; } for(int i = 0; i < nums.size(); ++i) { if(!used[i]) { vector<int> new_hand {hand.begin(), hand.end()}; new_hand.push_back(nums[i]); used[i] = true; backtrack(used, nums, res, new_hand, used_count + 1); used[i] = false; } } } };
![](https://kickstart.best/wp-content/uploads/2020/08/image-4-1024x755.png)
Another Submission
The new hand is not necessary, using pop_back() method of vector.
class Solution { public: vector<vector<int>> permute(vector<int>& nums) { vector<bool> used(nums.size(), false); vector<vector<int>> res; backtrack(used, nums, res, {}, 0); return res; } private: void backtrack(vector<bool>& used, vector<int>& nums, vector<vector<int>>& res, vector<int> hand, int used_count) { if(used_count == nums.size()) { res.push_back(hand); return; } for(int i = 0; i < nums.size(); ++i) { if(!used[i]) { hand.push_back(nums[i]); used[i] = true; backtrack(used, nums, res, hand, used_count + 1); hand.pop_back(); used[i] = false; } } } };
![](https://kickstart.best/wp-content/uploads/2020/08/image-6-1024x822.png)