• DFS解法的两道题 Leetcode 46 Permutations & Leetcode 78 Subset


    Leetcode 78 Subset

    Given a set of distinct integers, 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,3], a solution is:

    [
      [3],
      [1],
      [2],
      [1,2,3],
      [1,3],
      [2,3],
      [1,2],
      []
    ]

    题目解析:
    这种返回all possible的题就可以用bfs的方法来解啦~思路是先把array排序(因为题里要求是non-descending)
    然后思路是从num里面依次读取数字,存到ArrayList<Integer>的list里面, 然后再把list存到ArrayList<ArrayList<Integer>>的res里
    顺序是这样的[], [1], [1, 2], [1, 2, 3], [2], [2, 3], [3]
    记得边界检测
     1 public class Solution {
     2     public static List<List<Integer>> subsets(int[] S) {
     3         List<List<Integer>> res = new ArrayList<List<Integer>>();
     4         if(S == null || S.length == 0)
     5             return res;
     6         Arrays.sort(S);
     7         ArrayList<Integer> list = new ArrayList<Integer>();
     8         dfs(res, list, S, 0);
     9         return res;
    10     }
    11     public static void dfs(List<List<Integer>> res, ArrayList<Integer> list, int[] S, int pos){
    12         res.add(new ArrayList<Integer>(list));
    13         for(int i = pos; i < S.length; i++){
    14             list.add(S[i]);
    15             dfs(res, list, S, i+1);
    16             list.remove(list.size() - 1);
    17         }
    18     }
    19 }
    
    

    Leetcode 46 Permutations

    Given a collection of numbers, return all possible permutations.

    
    

    For example,
    [1,2,3] have the following permutations:
    [1,2,3][1,3,2][2,1,3][2,3,1][3,1,2], and [3,2,1].

    题目解析:

    这道题更是典型的DFS啦~直接用DFS模型就好了~至于检测某个数组的element是否被使用了这种情况就新建一个boolean的数组进行检测就好了~

    public class Solution {
        public static List<List<Integer>> permute(int[] num) {
            List<List<Integer>> res = new ArrayList<List<Integer>>();
            ArrayList<Integer> list = new ArrayList<Integer>();
            boolean[] flag = new boolean[num.length];
            dfs(res, list, num, flag);
            return res;
        }
        public static void dfs(List<List<Integer>> res, ArrayList<Integer> list, int[] num, boolean[] flag){
            if(list.size() == num.length){
                res.add(new ArrayList<Integer>(list));
                return;
            }
            for(int i = 0; i < num.length; i++){
                if(!flag[i]){
                    flag[i] = true;
                    list.add(num[i]);
                    dfs(res, list, num, flag);
                    list.remove(list.size() - 1);
                    flag[i] = false;
                }
            }
        }
    }
  • 相关阅读:
    建议自学
    大牛之术
    学习榜样
    .net源码
    练习题
    学习-如何克服拖延
    如何解决困难问题
    最近阅读
    如何学习一门新语言
    安全问题关注博客
  • 原文地址:https://www.cnblogs.com/sherry900105/p/4343779.html
Copyright © 2020-2023  润新知