开始学算法 x+2天 ===> 回溯探索第三章!哥布林深处(LeetCode刷题!!!)

跟着carl哥的第X+2天

x天是因为在医院躺了快三周,回到学校开始学习!!!
缺的会开始补回来的,我向天发誓

回溯算法基础模板

void backtracking(参数){

	//终止条件一般是当一个元素符合条件以后,将该元素存入结果集 然后返回到上一层再去向下遍历其他元素
    if(终止条件){
        存放结果;
        return;
    }
    
    //for循环就是用来遍历数组的每一个元素(横向遍历)
    for(选择:本层集合中元素(树中结点孩子的数量就是集合的大小)){
        处理节点;

		//递归向下遍历 在终止条件中判断是否符合条件
        backtracking(路径,选择列表); //递归

		//递归之后返回上一层后,再进行回溯处理,把原有下一层的元素去除 重新遍历该层中的其他元素
		//这便是回溯法
        回溯,撤销处理结果
    }
}

回溯思路(回溯三部曲):

  • 第一步:确定好递归后返回的参数(一般采用全局变量,不需要在回溯方法中传太多参数)

  • 第二步:就是确定好回溯法的终止条件 (在这道题是存储单一答案的数组大小 == k值)

  • 第三步:单层搜索的过程 (每一层我们应该怎么写 只看一层就不会乱 )

    其实回溯法就是暴力搜索,然后运用递归实现n个for循环。横向遍历是数组宽度,纵向遍历是递归。

回溯算法第三层【子集问题+排列问题】

开头第一只青哥布林:leetcode78.子集

给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。

说明:解集不能包含重复的子集。

示例:

  • 输入: nums = [1,2,3]
  • 输出:输出: [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]

思路:
这道题在三部曲中 没有什么限制条件 (没有模板里的if) 因为是每个节点都存入到结果集即可
然后直接套模板


答案:::

public class Test01 {

    static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
    static List<List<Integer>> res = new ArrayList<>();
    static LinkedList<Integer> path = new LinkedList<>();

    public static void main(String[] args) throws IOException {

        String[] strs = in.readLine().split(",");
        int[] nums = new int[strs.length];
        for (int i = 0; i < strs.length; i ++) {

            nums[i] = Integer.parseInt(strs[i]);
        }

        List<List<Integer>> result = subsets(nums);
        out.write(result.toString());
        out.flush();
        out.close();
    }

    public static List<List<Integer>> subsets(int[] nums) {

        if (nums == null || nums.length == 0) {
            return res;
        }

        backTrack(nums, 0);
        return res;
    }

    private static void backTrack(int[] nums, int startIndex) {

        //好像没啥限制条件
        res.add(new ArrayList<>(path));

        for (int i = startIndex; i < nums.length; i ++) {

            path.add(nums[i]);
            backTrack(nums, i + 1);
            path.removeLast();
        }
    }
}


一只赤哥布林:leetcode90.子集II

给定一个可能包含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。

说明:解集不能包含重复的子集。

示例1 :

输入: [1,2,2]
输出: [ [2], [1], [1,2,2], [2,2], [1,2], [] ]

思路:
与上题相比多了查重
也就是上一题的逻辑+前面学过的查重方法
试试看吧!


答案:

public class Test02 {

    static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
    static List<List<Integer>> res = new ArrayList<>();
    static LinkedList<Integer> path = new LinkedList<>();
    static boolean[] used = null;

    public static void main(String[] args) throws IOException {

        String[] strs = in.readLine().split(",");
        int[] nums = new int[strs.length];
        for (int i = 0; i < strs.length; i ++) {

            nums[i] = Integer.parseInt(strs[i]);
        }

        List<List<Integer>> result = subsetsWithDup(nums);
        out.write(result.toString());
        out.flush();
        out.close();
    }

    public static List<List<Integer>> subsetsWithDup(int[] nums) {

        if (nums == null || nums.length == 0) {
            return res;
        }
        used = new boolean[nums.length];
        Arrays.fill(used, false);
        Arrays.sort(nums);

        backTrack(nums, used, 0);
        return res;
    }

    private static void backTrack(int[] nums, boolean[] used, int startIndex) {

        res.add(new LinkedList<>(path));

        for (int i = startIndex; i < nums.length; i ++) {

            //查重
            if (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == false) {
                continue;
            }

            path.add(nums[i]);
            used[i] = true;
            backTrack(nums, used, i + 1);
            used[i] = false;
            path.removeLast();
        }
    }
}

一只等级高一点的十夫长:leetcode491.递增子序列

给定一个整型数组, 你的任务是找到所有该数组的递增子序列,递增子序列的长度至少是2。

示例 1:

输入: [4, 6, 7, 7]
输出: [[4, 6], [4, 7], [4, 6, 7], [4, 6, 7, 7], [6, 7], [6, 7, 7], [7,7], [4,7,7]]
说明:
	给定数组的长度不会超过15。
	数组中的整数范围是 [-100,100]。
	给定数组中可能包含重复数字,相等的数字应该被视为递增的一种情况。

思路:

  • 跟上一道题有相似之处,但也有且只有相似之处。 终止条件:递增子序列的长度至少是2
  • path中的最右边的数(path中最大值)与剩下区间中所有数判断,而不仅仅只是与下一个数判断
  • 同一父节点下的同层上使用过的元素就不能在使用,但因为不能排序,所以跟上一题思路不同
  • 可以用一个map来存储同一层用过的元素来查重

答案:

public class Test03 {

    static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
    static List<List<Integer>> res = new ArrayList<>();
    static ArrayList<Integer> path = new ArrayList<>();
    static HashMap<Integer, Integer> map = new HashMap<>();

    public static void main(String[] args) throws IOException {

        String[] strs = in.readLine().split(",");
        int[] nums = new int[strs.length];
        for (int i = 0; i < strs.length; i ++) {

            nums[i] = Integer.parseInt(strs[i]);
        }

        List<List<Integer>> result = findSubsequences(nums);
        out.write(result.toString());
        out.flush();
        out.close();
    }

    public static List<List<Integer>> findSubsequences(int[] nums) {

        backTrack(nums,0);
        return res;
    }

    private static void backTrack(int[] nums, int startIndex) {

        if (path.size() >= 2) {
            res.add(new ArrayList<>(path));
        }

        for (int i = startIndex; i < nums.length; i ++) {

            if (!path.isEmpty() && path.get(path.size() - 1) > nums[i]) {
                continue;
            }

            if (map.getOrDefault(nums[i], 0) >= 1) {
                continue;
            }
            map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
            path.add(nums[i]);
            backTrack(nums, i + 1);
            path.remove(path.size() - 1);
        }

    }
}

第一只投掷十夫长:leetcode46.全排列

给定一个 没有重复 数字的序列,返回其所有可能的全排列。

实例1:

  • 输入: [1,2,3]
  • 输出: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ]

思路:
主要还是回溯三部曲

  • 返回值
  • 终止条件 只要path中存储元素 = nums的长度
  • 单层搜索逻辑 用一个used[]来记录使用过的元素即可

答案

public class Test04 {

    static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
    static List<List<Integer>> res = new ArrayList<>();
    static ArrayList<Integer> path = new ArrayList<>();
    static boolean[] used = null;

    public static void main(String[] args) throws IOException {

        String[] strs = in.readLine().split(",");
        int[] nums = new int[strs.length];
        for (int i = 0; i < strs.length; i ++) {

            nums[i] = Integer.parseInt(strs[i]);
        }

        List<List<Integer>> result = permute(nums);
        out.write(result.toString());
        out.flush();
        out.close();
    }

    private static List<List<Integer>> permute(int[] nums) {

        used = new boolean[nums.length];
        Arrays.fill(used, false);
        backTrack(nums, used);
        return res;
    }

    private static void backTrack(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;
            } else {
                path.add(nums[i]);
                used[i] = true;
                backTrack(nums, used);
                used[i] = false;
                path.remove(path.size() - 1);
            }
        }
    }
}

哥布林突击部队:leetcode47.全排列 II

给定一个可包含重复数字的序列 nums ,按任意顺序 返回所有不重复的全排列。

实例1:

  • 输入:nums = [1,1,2]
  • 输出: [[1,1,2], [1,2,1], [2,1,1]]

实例2:

  • 输入:nums = [1,2,3]
  • 输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

提示:

  • 1 <= nums.length <= 8
  • -10 <= nums[i] <= 10

思路:
上一章的查重技巧+上一题的做法即可


答案

public class Test05 {
    static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
    static List<List<Integer>> res = new ArrayList<>();
    static ArrayList<Integer> path = new ArrayList<>();
    static boolean[] used = null;

    public static void main(String[] args) throws IOException {

        String[] strs = in.readLine().split(",");
        int[] nums = new int[strs.length];
        for (int i = 0; i < strs.length; i ++) {

            nums[i] = Integer.parseInt(strs[i]);
        }

        List<List<Integer>> result = permute(nums);
        out.write(result.toString());
        out.flush();
        out.close();
    }

    private static List<List<Integer>> permute(int[] nums) {

        used = new boolean[nums.length];
        Arrays.fill(used, false);
        Arrays.sort(nums);
        backTrack(nums, used);
        return res;
    }

    private static void backTrack(int[] nums, boolean[] used) {

        if (path.size() == nums.length) {
            res.add(new ArrayList<>(path));
            return;
        }

        for (int i = 0; i < nums.length; i ++) {
            if (i > 0 &&!used[i - 1] && nums[i] == nums[i - 1] ) {
                continue;
            }
            if (used[i]) {
                continue;
            } else {
                path.add(nums[i]);
                used[i] = true;
                backTrack(nums, used);
                used[i] = false;
                path.remove(path.size() - 1);
            }
        }
    }
}

自我总结

懂了一点点回溯了 万事开头难 大家加油!!!
少年仍需努力

朋友仍需努力 一起加油
兄弟萌冲啊!

大概就是这样,大家懂了吗 有什么不懂的评论区评论或者私信我吧!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值