给定一个没有重复数字的序列,返回其所有可能的全排列。
示例:
输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
dfs+递归:夹逼递归
class Solution {
public:
vector<vector<int>> permute(vector<int>& nums) {
vector<int> tmp;
vector<vector<int>> ans;
int len = nums.size();
vector<bool> idx(len,0); //1代表该数进入排列,0相反
dfs(ans,tmp,idx,nums,len);
return ans;
}
void dfs(vector<vector<int>> &ans,vector<int> &tmp,vector<int> &idx,vector<int> &nums,int len)
{
if(tmp.size() == nums.size())
{
ans.push_back(tmp);
return;
}
for(int i = 0; i < len;i++)
{
if(idx[i] == 1)continue;
idx[i] = 1;
tmp.push_back(nums[i]);
dfs(ans,tmp,idx,nums,len);
tmp.pop_back();
idx[i] = 0;
}
}
};
func permute(nums []int) [][]int {
n := len(nums)
tmp := make([]int,n)
ans := make([][]int,0)
idx := make([]bool,n) //默认0
dfs(&ans,idx,tmp,nums,n,0)
return ans
}
func dfs(ans *[][]int,idx []bool,tmp []int,nums []int,n int,cur int) {
if cur == n {
t := make([]int,n)
copy(t,tmp) //必须copy出来,不然共享变量底层,答案会输出一样
*ans = append(*ans,t)
return
}
for i := 0;i < n;i++{
if idx[i] == true{
continue
}
idx[i] = true
tmp[cur] = nums[i]
dfs(ans,idx,tmp,nums,n,cur+1)
idx[i] = false
}
}