穷举vs暴搜vs深搜vs回溯vs剪枝 算法专题

一. 全排列

全排列

java 复制代码
class Solution {
    List<List<Integer>> ret;
    List<Integer> path;
    boolean[] check;
    public List<List<Integer>> permute(int[] nums) {
        ret = new ArrayList<>();//存放结果
        path = new ArrayList<>();存放每个路径的path
        check = new boolean[nums.length];//记录是否被使用, 对应是下标

        dfs(nums);
        return ret;
    }

    public void dfs(int[] nums){
        if(path.size() == nums.length){//全部遍历完
            ret.add(new ArrayList<>(path));//添加结果
            return;
        }
        for(int i = 0; i < nums.length; i++){
            if(!check[i]){
                path.add(nums[i]);
                check[i] = true;
                dfs(nums);
                //还原现场
                check[i] = false;
                path.remove(path.size() - 1);
            }
        }
    }
}

二. 子集

子集

先画决策树, 再设计代码

解法一:

java 复制代码
class Solution {
    List<List<Integer>> ret;
    List<Integer> path;
    public List<List<Integer>> subsets(int[] nums) {
        ret = new ArrayList<>();
        path = new ArrayList<>();

        dfs(nums, 0);
        return ret;
    }

    public void dfs(int[] nums, int i){//要选择的下标
        if(i == nums.length){
            ret.add(new ArrayList<>(path));
            return ;
        }
        //选
        path.add(nums[i]);
        dfs(nums, i + 1);
        //恢复现场
        path.remove(path.size() - 1);
        //不选
        dfs(nums, i + 1);
    }
}

解法二: 按照数量添加

java 复制代码
class Solution {
    List<List<Integer>> ret;
    List<Integer> path;

    public List<List<Integer>> subsets(int[] nums) {
        ret = new ArrayList<>();
        path = new ArrayList<>();

        dfs(nums, 0);
        return ret;
    }

    public void dfs(int[] nums, int pos) {
        ret.add(new ArrayList<>(path));//每个节点全部加入
        for(int i = pos; i < nums.length; i++){
            path.add(nums[i]);
            dfs(nums, i + 1);//只能添加此时下标后面的, 防止重复
            path.remove(path.size() - 1);//恢复现场
        }

    }
}
相关推荐
张李浩8 小时前
Leetcode 054螺旋矩阵 采用方向数组解决
算法·leetcode·矩阵
big_rabbit05028 小时前
[算法][力扣101]对称二叉树
数据结构·算法·leetcode
美好的事情能不能发生在我身上8 小时前
Hot100中的:贪心专题
java·数据结构·算法
2301_821700539 小时前
C++编译期多态实现
开发语言·c++·算法
xixihaha13249 小时前
C++与FPGA协同设计
开发语言·c++·算法
小小怪7509 小时前
C++中的函数式编程
开发语言·c++·算法
xixixiLucky10 小时前
编程入门算法题---小明爬楼梯求爬n层台阶一共多少种方法
算法
剑锋所指,所向披靡!10 小时前
数据结构之线性表
数据结构·算法
m0_6727033112 小时前
上机练习第49天
数据结构·算法
样例过了就是过了12 小时前
LeetCode热题100 N 皇后
数据结构·c++·算法·leetcode·dfs·深度优先遍历