LeetCode 46 全排列
LeetCode46 全排列
题目描述
给定一个 没有重复 数字的序列,返回其所有可能的全排列。
样例
输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
算法分析
dfs 枚举位置
时间复杂度
Java代码
class Solution {
static List<List<Integer>> ans = new ArrayList<List<Integer>>();
static boolean[] st;
static List<Integer> t = new ArrayList<Integer>();
static void dfs(int u, int[] nums){
int n = nums.length;
if(u == n){
ans.add(new ArrayList<Integer>(t));
return ;
}
for(int i = 0; i<n;i++){
if(st[i]) continue;
t.add(nums[i]);
st[i] = true;
dfs(u+1,nums);
st[i] = false;
t.remove(t.size()-1);
}
}
public List<List<Integer>> permute(int[] nums) {
ans.clear();
int n = nums.length;
st = new boolean[n+10];
dfs(0,nums);
return ans;
}
}

浙公网安备 33010602011771号