• 深度优先搜索算法(DFS)以及leetCode的subsets II


    深度优先搜索算法(depth first search),是一个典型的图论算法。所遵循的搜索策略是尽可能“深”地去搜索一个图。

    算法思想是:

        对于新发现的顶点v,如果它有以点v为起点的未探测的边,则沿此边继续探测下去。当顶点v的所有边都已被探寻结束,则回溯到到达点v的先辈节点。以相同方法一直回溯到源节点为止。如果图中还有未被发现的顶点,则选择其中一个作为源顶点,重复以上的过程。最后的结果是一些不相交的深度优先树。

    leetCode中的应用:

    Given a collection of integers that might contain duplicates, S, return all possible subsets.

    Note:

    • Elements in a subset must be in non-descending order.
    • The solution set must not contain duplicate subsets.

    For example,
    If S = [1,2,2], a solution is:

    [
      [2],
      [1],
      [1,2,2],
      [2,2],
      [1,2],
      []
    ]
    可以使用DFS来解答,通过构造二叉树,然后得到所有子集为二叉树的所有叶子节点,然后使用DFS算法,将所有叶子节点输出。
    构造二叉树如下:

    实现代码如下(参考网上):

     public List<List<Integer>> subsetsWithDup(int[] num) {
            List<List<Integer>> res = new ArrayList<List<Integer>>();
           if(num == null ||num.length == 0){
               return res;
           }
           int len = num.length;
           Arrays.sort(num);//对数组里的数排序
           for(int i=1; i<len+1; i++){
               ArrayList<Integer> numList = new ArrayList<Integer>();
               dfs(res,numList,num,0,i);
           } 
           res.add(new ArrayList<Integer>());
           return res;
        }
        private void dfs(List<List<Integer>> res, ArrayList<Integer> numList,
                int[] num, int start, int k) {
            if(numList.size() == k){
                 res.add(new  ArrayList<Integer>(numList));
                 return;
            }
            ArrayList<Integer> allList = new ArrayList<Integer>();
            for(int i=start; i<num.length; i++){
                if(allList.contains(num[i])) continue;
                allList.add(num[i]);
                numList.add(num[i]);
                dfs(res, numList, num, i+1, k);
                numList.remove(numList.size()-1);
            }
        }
  • 相关阅读:
    C#对List排序的三种方式的比较
    unity跨平台及热更新学习笔记-C#中通过程序域实现DLL的动态加载与卸载
    总结下C#中有关结构体的几个问题
    C#中通过逻辑^(异或)运算交换两个值隐藏的巨坑!!!
    unity实现批量删除Prefab上Miss的脚本组件
    Oracle构造列思想,decode,case,sgin,pivot四大金刚
    Oracle-计算岁数
    Oracle 集合
    Oracle 综合例子应用01
    Oracle 事实表,维表,多对多
  • 原文地址:https://www.cnblogs.com/Eunice-mogu/p/3960474.html
Copyright © 2020-2023  润新知