2025-07-05 18:04:10 +08:00

82 lines
2.4 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package backtrack;
import java.util.ArrayList;
import java.util.List;
/**
* 题目: 46. 全排列 (permute)
* 描述:给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。
*示例 1
* 输入nums = [1,2,3]
* 输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
* 示例 2
* 输入nums = [0,1]
* 输出:[[0,1],[1,0]]
* 示例 3
* 输入nums = [1]
* 输出:[[1]]
* 链接https://leetcode.cn/problems/permutations/
*/
//二刷会做
public class Permute {
void dfs(List<List<Integer>>res,List<Integer>path,int[] nums,boolean[] used){
if(path.size()==nums.length) {
res.add(new ArrayList<>(path));
return;
}
for (int i = 0; i < nums.length; i++) {
if(used[i])continue;
used[i]=true;
path.add(nums[i]);
dfs(res,path,nums,used);
path.remove(path.size()-1);
used[i]=false;
}
}
public List<List<Integer>> permute2(int[] nums) {
List<List<Integer>>res=new ArrayList<>();
List<Integer>path=new ArrayList<>();
boolean[] used=new boolean[nums.length];
dfs(res,path,nums,used);
return res;
}
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
// 用来标记数组中数字是否被使用
boolean[] used = new boolean[nums.length];
List<Integer> path = new ArrayList<>();
backtrack(nums, used, path, res);
return res;
}
private void backtrack(int[] nums, boolean[] used, List<Integer> path, List<List<Integer>> res) {
// 当path中元素个数等于nums数组的长度时说明已构造出一个排列
if (path.size() == nums.length) {
res.add(new ArrayList<>(path));
return;
}
// 遍历数组中的每个数字
for (int i = 0; i < nums.length; i++) {
// 如果该数字已经在当前排列中使用过,则跳过
if (used[i]) {
continue;
}
// 选择数字nums[i]
used[i] = true;
path.add(nums[i]);
// 递归构造剩余的排列
backtrack(nums, used, path, res);
// 回溯:撤销选择,尝试其他数字
path.remove(path.size() - 1);
used[i] = false;
}
}
}