题目描述:
Given a collection of distinct numbers, return all possible permutations.
For example,[1,2,3]
have the following permutations:[1,2,3]
, [1,3,2]
, [2,1,3]
, [2,3,1]
, [3,1,2]
, and [3,2,1]
.
解题思路:
递归方法,用一个数组来记录当前元素是否已经被访问
1 class Solution { 2 public: 3 vector<vector<int>> permute(vector<int>& nums) { 4 vector<vector<int>> result; 5 vector<int> elem; 6 vector<bool> visited(nums.size(), false); 7 permute(nums, visited, result, elem); 8 return result; 9 } 10 private: 11 void permute(const vector<int> &nums, vector<bool> &visited, vector<vector<int>> &result, vector<int> &elem) { 12 if (nums.size() == elem.size()) { 13 result.push_back(elem); 14 return; 15 } 16 17 for (int i = 0; i < nums.size(); ++i) { 18 if (!visited[i]) { 19 visited[i] = true; 20 elem.push_back(nums[i]); 21 permute(nums, visited, result, elem); 22 visited[i] = false; 23 elem.pop_back(); 24 } 25 } 26 } 27 };