AcWing 51. 数字排列
原题链接
简单
Java版本,涉及到stream流
class Solution {
public static ArrayList<List<Integer>> res = new ArrayList();
public List<List<Integer>> permutation(int[] nums) {
Arrays.sort(nums);
int[] ans = new int[nums.length];
dfs(nums, 0, 0, 0, ans);
return res;
}
public static void dfs(int[] nums, int u, int start, int state, int[] ans){
if( u == nums.length) {
List<Integer> list = Arrays.stream(ans).boxed().collect(Collectors.toList());
res.add(list);
return;
}
for(int i = start; i < nums.length; i ++){
if((state >> i & 1) == 0 ){
ans[i] = nums[u];
if(u + 1 < nums.length && nums[u] == nums[u + 1]) dfs(nums, u + 1, i + 1, state + (1 << i), ans);
else dfs(nums, u + 1, 0, state + (1 << i), ans);
}
}
}
}