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] ]
思路一:二话不说,经典题, 回溯。
1 class Solution { 2 public: 3 vector<vector<int>> permute(vector<int>& nums) { 4 sort(nums.begin(), nums.end()); 5 int len = nums.size(); 6 vector<bool> visited(len, false); 7 vector<vector<int> > res; 8 vector<int> tmp; 9 dfs(0, len, nums, tmp, res, visited); 10 return res; 11 } 12 private: 13 void dfs(int start, int len, vector<int> &nums, vector<int> &v, vector<vector<int> > &res, vector<bool> &visited) { 14 if (start == len) { 15 res.push_back(v); 16 return ; 17 } 18 for (int i = 0; i < len; i++) { 19 if (visited[i] == false) { 20 visited[i] = true; 21 v.push_back(nums[i]); 22 dfs(start + 1, len, nums, v, res, visited); 23 v.pop_back(); 24 visited[i] = false; 25 } 26 } 27 } 28 };
思路二:
1 class Solution { 2 public: 3 vector<vector<int>> permute(vector<int>& nums) { 4 sort(nums.begin(), nums.end()); 5 int len = nums.size(); 6 vector<vector<int> > res; 7 dfs(0, len, nums, res); 8 return res; 9 } 10 private: 11 void dfs(int start, int len, vector<int> &nums, vector<vector<int> > &res) { 12 if (start == len) { 13 res.push_back(nums); 14 return ; 15 } 16 for (int i = start; i < len; i++) { 17 swap(nums[start], nums[i]); 18 dfs(start + 1, len, nums, res); 19 swap(nums[start], nums[i]); 20 } 21 } 22 };