46 Permutations

Medium

333697Add to ListShare

Given a collection of distinct integers, return all possible permutations.

Example:

1
2
3
4
5
6
7
8
9
10
Input: [1,2,3]
Output:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
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
35
36
37
38
class Solution {
public:
vector<vector<int>>res;
vector<bool> vis;//表示这个解遇到过了;

void backtrace(const vector<int>&nums,vector<int>&track,int index){
//index记录vis的编号;
if(index==nums.size()){
res.push_back(track);
return;
}
for(int i=0;i<nums.size();i++){
if(vis[i]){
;
}else{
//没有访问过;
vis[i]=true;
track.push_back(nums[i]);
backtrace(nums,track,index+1);
track.pop_back();
vis[i]=false;

}
}
}
vector<vector<int>> permute(vector<int>& nums) {
res.clear();
if(nums.size()==0){
return res;
}
vis = vector<bool>(nums.size(), false);
vector<int> track;
backtrace(nums,track,0);
return res;


}
};