LeetCode46
class Solution {
// 直接给类添加表示状态的属性
boolean is[];
// 保存结果的属性
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> permute(int[] nums) {
is = new boolean[nums.length];
dfs(nums, new ArrayList<Integer>());
return res;
}
public void dfs(int[] nums, List<Integer> list){
if(list.size() == nums.length){
// 这里需要return的是list的复制的值,不能直接是list,因为后面回溯还会用到
res.add(new ArrayList<Integer>(list));
return;
}
for(int i = 0; i < nums.length; i++){
if(!is[i]){
// 通过状态判断,如果没被访问过就访问
list.add(nums[i]);
// 随后添加访问状态
is[i] = true;
// 递归继续访问
dfs(nums, list);
// 走到这里就说明递归完成了,那么就开始回溯,清除递归前的所有状态
list.remove(list.size() - 1);
// 上面访问的元素已经被清除掉了,那么对应的状态也要是未访问
is[i] = false;
}
}
}
}
LeetCode47
// 这里和上一题差不多,但是需要注意的是这里要输出所有不重复的全排,即排列时如果有重复的元素的话
// 那么会导致的就是同样的数字,但是会重复使用,例如[2,1,1]里面两个1就会重复使用
class Solution {
boolean [] is;
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> permuteUnique(int[] nums) {
is = new boolean[nums.length];
// 这里先进行一个排序,确保相同的元素都是相邻的,如果相同的元素不相邻的话,就不能用下面 的if来判断,就会导致出现重复使用的元素
Arrays.sort(nums);
dfs(nums, new ArrayList<Integer>());
return res;
}
public void dfs(int[] nums, List<Integer> list){
if(list.size() == nums.length){
this.res.add(new ArrayList<>(list));
return;
}
for(int i = 0; i < nums.length; i++){
// 首先判断当前元素有没有使用过,如果使用过这跳过
// 如果没使用过 就判断是否和前一个元素相等,相等并且没使用过的话,就直接跳过
if(this.is[i] || (i > 0 && is[i-1] == false && nums[i] == nums[i-1] )){
continue;
}
list.add(nums[i]);
is[i] = true;
dfs(nums, list);
list.remove(list.size() - 1);
is[i] = false;
}
}
}
LeetCode77
class Solution {
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> combine(int n, int k) {
dfs(1, k, new ArrayList<Integer>(), n);
return res;
}
public void dfs(int index, int k, List<Integer> list, int n){
if(list.size() == k){
res.add(new ArrayList<>(list));
return;
}
for(int i = index; i <= n; i++) {
list.add(i);
dfs(i+1, k, list, n);
list.remove(list.size() - 1);
}
}
}
LeetCode78
class Solution {
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> subsets(int[] nums) {
dfs(nums, 0, new ArrayList<>());
return res;
}
// 这题不要求全排列,就只需要排列组合就行,因此一条路走到头,回溯,换条路即可
public void dfs(int[] nums,int index, List<Integer> list){
res.add(new ArrayList<>(list));
for(int i = index; i < nums.length; i++){
list.add(nums[i]);
dfs(nums, i + 1, list);
list.remove(list.size() - 1);
}
}
}
dfs排列组合
最新推荐文章于 2024-03-20 12:29:19 发布