# LeetCode Permutations

LeetCode 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]
]```

```class Solution {
public:
void work(vector<vector<int>>& ans, vector<int>& tmp, vector<int>& nums, vector<int>& flag) {
if (tmp.size() == nums.size()) {
ans.push_back(tmp);
}
else {
for (int i = 0; i < flag.size(); i++) {
if (flag[i] == 1) {
vector<int> next = tmp;
next.push_back(nums[i]);
flag[i] = 0;
work(ans, next, nums, flag);
flag[i] = 1;
}
}
}
}
vector<vector<int>> permute(vector<int>& nums) {
vector<int> flag(nums.size(), 1);
vector<vector<int>> ans;
vector<int> tmp;
work(ans, tmp, nums, flag);
return ans;
}
};
```

```class Solution {
private:

void DFS(const vector<int>& nums, vector<int>& visited, vector<int>& candidate, vector<vector<int>>& ans) {
if(candidate.size() == nums.size()) {
ans.push_back(candidate);
return;
}

for(int i = 0; i < nums.size(); ++i) {
if(visited[i] == 0) {
visited[i] = 1;
candidate.push_back(nums[i]);
DFS(nums, visited, candidate, ans);
visited[i] = 0;
candidate.pop_back();
}
}
}

public:
vector<vector<int>> permute(vector<int>& nums) {
vector<int> visited(nums.size(), 0), candidate;
vector<vector<int>> ans;
DFS(nums, visited, candidate, ans);
return ans;
}
};
```

```class Solution {
private:

void DFS(vector<int>& nums, vector<vector<int>>& ans, int start) {
if(start == nums.size()) {
ans.push_back(nums);
return;
}
for(int i = start; i < nums.size(); ++i) {
swap(nums[i], nums[start]);
DFS(nums, ans, start + 1);
swap(nums[i], nums[start]);
}
}

public:
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int>> ans;
DFS(nums, ans, 0);
return ans;
}
};
```