46. Permutations
题目 46. Permutations
思路分析
c++中有全排列函数next_permutation java没有 只能用dfs写
代码实现
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
boolean[] st;
public List<List<Integer>> permute(int[] nums) {
int n = nums.length;
st = new boolean[n];
dfs(nums,0);
return res;
}
void dfs(int[] nums,int u){
if(u==nums.length){
res.add(new ArrayList<>(path));
return;
}
for(int i=0;i<nums.length;i++){
if(!st[i]){
st[i]=true;
path.add(nums[i]);
dfs(nums,u+1);
path.remove(path.size()-1);
st[i]=false;
}
}
}
}
💬 评论