Given a collection of distinct integers, return all possible permutations.
Example:
Input: [1,2,3]
Output:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 class Solution { 2 public: 3 void build(vector<bool>visited, vector<int>nums, vector<vector<int>>&ans,vector<int>now) { 4 int flag = false; 5 int n = nums.size(); 6 for(int i=0;i<n;i++) 7 if (!visited[i]) { 8 visited[i] = true; 9 now.push_back(nums[i]); 10 build(visited, nums, ans, now); 11 visited[i] = false; 12 now.pop_back(); 13 flag = true; 14 } 15 if (!flag)ans.push_back(now); 16 } 17 vector<vector<int>> permute(vector<int>& nums) { 18 vector<bool>visited(nums.size(), false); 19 vector<vector<int>>ans; 20 build(visited, nums, ans, vector<int>()); 21 return ans; 22 } 23 };
一开始的暴力方法↑ 不出所料很慢
换了一种也没好多少
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 class Solution { 2 public: 3 vector<vector<int>> permute(vector<int>& nums) { 4 vector<vector<int>>ans; 5 ans.push_back(vector<int>(1, nums[0])); 6 for (int i = 1; i < nums.size(); i++) { 7 vector<vector<int>>tmp = ans; 8 ans.clear(); 9 for (int j = 0; j < tmp.size(); j++) { 10 vector<int>now = tmp[j]; 11 for (int k = 0; k <= now.size(); k++) { 12 now.insert(now.begin() + k, nums[i]); 13 ans.push_back(now); 14 now.erase(now.begin() + k); 15 } 16 } 17 } 18 return ans; 19 } 20 };
(算了算了