LeetCode 46. Permutations
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],
[3,2,1]
]
明显的全排列,直接用C++
里面全排列函数写一遍,最后发现数组存在负数情况时,会莫名少了好多情况, 于是直接DFS
手写一个全排列。
class Solution
{
void dfs(int b, int e, vector<int>& nums, vector<vector<int>> &ans)
{
if(b == e)
{
ans.push_back(nums);
return;
}
for(int i=b; i <= e; ++ i)
{
swap(nums[i], nums[b]);
dfs(b+1, e, nums, ans);
swap(nums[i], nums[b]);
}
}
public:
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int>> ans;
dfs(0, nums.size() - 1, nums, ans);
return ans;
}
};