Given a list of numbers, return all possible permutations.
Have you met this question in a real interview?
Yes
Example
For nums =
[1,2,3]
, the permutations are:[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
Challenge
Do it without recursion.
没啥好说的。。。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | class Solution { public: /** * @param nums: A list of integers. * @return: A list of permutations. */ vector<vector<int> > permute(vector<int> nums) { // write your code here vector<vector<int>> result; vector<int> solution; if (nums.size()==0) return result; sort(nums.begin(), nums.end()); vector<bool> visited(nums.size(), false); dfs(nums,result,solution, visited); return result; } void dfs(vector<int>& nums, vector<vector<int>>& result, vector<int>& solution, vector<bool>& visited){ if (solution.size()==nums.size()){ result.push_back(solution); return; } for (int i=0; i<nums.size(); i++){ if (visited[i]) continue; visited[i]=true; solution.push_back(nums[i]); dfs(nums,result, solution, visited); visited[i]=false; solution.pop_back(); } } }; |
No comments:
Post a Comment