[LeetCode]Permutations
Permutations
Given a collection of 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]
.
递归实现,回溯。这是一类题目。
遍历所有可能,符合条件放入结果中。
class Solution { public: void dfs(int length,vector<int> nums,vector<vector<int>>& result) { if(length==nums.size()) { result.push_back(nums); return; } for(int i=length;i<nums.size();i++) { swap(nums[length],nums[i]); dfs(length+1,nums,result); swap(nums[length],nums[i]); } } vector<vector<int>> permute(vector<int>& nums) { vector<vector<int>> result; dfs(0,nums,result); return result; } };