AcWing 51. 数字排列
原题链接
中等
作者:
君离
,
2024-04-26 22:49:48
,
所有人可见
,
阅读 4
题目描述
class Solution {
public List<List<Integer>> permutation(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
int[] used = new int[nums.length];
backtracking(new ArrayList<>(nums.length), used, nums, res );
return res;
}
public void backtracking(List<Integer> data, int[] used, int[] nums,List<List<Integer>> res){
//结果
if(data.size() == nums.length){
res.add(new ArrayList<>(data));
return;
}
//遍历
for (int i = 0; i < nums.length; i++) {
if(i < nums.length - 1 && nums[i] == nums[i + 1] && used[i] == used[i + 1]) continue;
if(used[i] == 0){
//放入数据
used[i] = 1;
data.add(nums[i]);
backtracking(data, used, nums, res);
//撤销
used[i] = 0;
data.remove(data.size() - 1);
}
}
}
}