leetcode DFS

简介: SummaryDFS problems have two kinds: One to get the number of all solutions.

Summary

  • DFS problems have two kinds: One to get the number of all solutions. The other is to get all the solutions itself.
    • To get the total number of solutions, usually you can use dynamic programming.
    • To get all the solution, there is a fixed solution style. And you need to determine where it doesn’t give out.
# main method 
res = []
self.helper(....)
return res

# auxiliary method
def helper(...):
    if proper:
        res.append()
        return
    for x in xrange(start,end):
        do something
        self.helper(...)
        undo something

leetcode 46 Permutations

Question

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].

Solution

recursion swap

Swap the current value and each of the values followed, then solve the rest permutation.

class Solution(object):
    def permute(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        res = []
        self.helper(nums,0,res)
        return res

    def helper(self,nums,start,res):
        if start == len(nums):
            res.append(list(nums))
            return
        for i in xrange(start,len(nums)):
            if not self.contain_duplication(nums,start,i):
                nums[start],nums[i] = nums[i],nums[start]
                self.helper(nums,start+1,res)
                nums[start],nums[i] = nums[i],nums[start]
    def contain_duplication(self,nums,start,end):
        for i in xrange(start,end):
            if nums[i] == nums[end]:
                return True
  • increase insert
    Every turn add a value in every possible position, and next turn and the new value on the base of the last turn. Use set to delete the duplication.
class Solution(object):
    def permute(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        res = []
        res.append([])
        for i in xrange(len(nums)):
            s = set()
            for lst in res:
                for j in xrange(len(lst)+1):
                    lst.insert(j,nums[i])
                    s.add(tuple(lst))
                    del lst[j]
            res = [list(t) for t in s]
        return res

leetcode 77 Combinations

Question

Given two integers n and k, return all possible combinations of k numbers out of 1 … n.

For example,
If n = 4 and k = 2, a solution is:

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

Solution

Recursion, when find a solution, back to the next value.

class Solution(object):
    def combine(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: List[List[int]]
        """
        res = []
        self.helper(n,k,[],res,1)
        return res

    def helper(self, n, k, lst, res, start):
        if len(lst) == k:
            res.append(list(lst))
            return
        for i in xrange(start,n+1):
            lst.append(i)
            self.helper(n,k,lst,res,i+1)
            lst.pop()

leetcode 39 Combination Sum

Question

Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

Solution

Different from above, this time it is allowed to reuse the elements, So you have to start at i, not i+1.

class Solution(object):
    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        res = []
        candidates.sort()
        self.helper(candidates,0,target,[],res)
        return res

    def helper(self,candidates,start,target,lst,res):
        if target == 0:
            res.append(list(lst))
            return
        elif target < 0:
            return
        for i in xrange(start,len(candidates)):
            if i == start or candidates[i] != candidates[i-1]: 
                lst.append(candidates[i])
                self.helper(candidates,i,target-candidates[i],lst,res)
                lst.pop()

leetcode 40 Combination Sum II

Question

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

Each number in C may only be used once in the combination.

Note:
All numbers (including target) will be positive integers.
Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
The solution set must not contain duplicate combinations.

Solution

The only difference from above is that every time it begins at the next point.

class Solution(object):
    def combinationSum2(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        res = []
        candidates.sort()
        self.helper(candidates,target,0,[],res)
        return res

    def helper(self,candidates,target,start,lst,res):
        if target <= 0:
            if target == 0:
                res.append(list(lst))
            return
        for i in xrange(start,len(candidates)):
            if i == start or candidates[i] != candidates[i-1]:
                lst.append(candidates[i])
                self.helper(candidates,target-candidates[i],i+1,lst,res)
                lst.pop()

leetcode 216 Combination Sum III

Question

Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.

Ensure that numbers within the set are sorted in ascending order.

Solution

Same to above.

class Solution(object):
    def combinationSum3(self, k, n):
        """
        :type k: int
        :type n: int
        :rtype: List[List[int]]
        """
        res = []
        self.helper(k,n,1,[],res)
        return res

    def helper(self,k,n,start,lst,res):
        if k == 0 or n <= 0:
            if k == 0 and n == 0:
                res.append(list(lst))
            return
        for i in xrange(start,10):
            lst.append(i)
            self.helper(k-1,n-i,i+1,lst,res)
            lst.pop()
目录
相关文章
|
2天前
|
算法 定位技术
【leetcode】剑指 Offer II 105. 岛屿的最大面积-【深度优先DFS】
【leetcode】剑指 Offer II 105. 岛屿的最大面积-【深度优先DFS】
10 0
|
11月前
|
算法
从三道leetcode掌握深度优先搜索(DFS)
前言 无论在算法面试还是刷题中,深度优先搜索(DFS)和广度优先搜索(BFS)都是一个绕不过去的坎。不同于数组的从左至右遍历,循环常用于一维数据结构的遍历。而DFS和BFS则常用于多维数据结构的遍历,最常见的莫过于嵌套结构的多叉树了。
|
12月前
|
人工智能 算法 BI
LeetCode 周赛 341 场,模拟 / 树上差分 / Tarjan 离线 LCA / DFS
上周末有单双周赛,双周赛我们讲过了,单周赛那天早上有事没参加,后面做了虚拟竞赛,然后整个人就不好了。前 3 题非常简单,但第 4 题有点东西啊,差点就放弃了。最后,被折磨了一个下午和一个大夜总算把第 4 题做出来了,除了新学的 Tarjon 离线算法,这道题还涉及到树上差分、前缀和、DFS、图论等基础知识,几度被折磨得想要放弃。这种感觉,似乎和当年在 LeetCode 上做前 10 题的时候差不多哈哈。
64 0
|
人工智能 Java BI
力扣207:课程表(Java拓扑排序:bfs+dfs)
力扣207:课程表(Java拓扑排序:bfs+dfs)
101 0
力扣200:岛屿数量(Java dfs+bfs)
给你一个由 '1'(陆地)和 '0'(水)组成的的二维网格,请你计算网格中岛屿的数量。 岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
Leetcode-每日一题1106. 解析布尔表达式(DFS模拟栈)
题目意思很简单让你去判断与或非布尔表达式的结果,我们可以看布尔表达式看成一棵树,需要我们解决的是从最底层的嵌套布尔表达式产生的结果不断向上的结果
75 1
Leetcode-每日一题1106. 解析布尔表达式(DFS模拟栈)
leetcode-10. 正则表达式匹配(DFS)
正则表达式是对字符串(包括普通字符(例如,a 到 z 之间的字母)和特殊字符(称为“元字符”))操作的一种逻辑公式,就是用事先定义好的一些特定字符及这些特定字符的组合,组成一个“规则字符串”,这个“规则字符串”用来表达对字符串的一种过滤逻辑。正则表达式是一种文本模式,该模式描述在搜索文本时要匹配的一个或多个字符串。
35 0
leetcode-10. 正则表达式匹配(DFS)
|
算法 Java C++
力扣429 - N叉树的层序遍历【BFS+DFS】
详细绘图教学和动画制作,附有BFS和DFS的万能模板,来解决二叉树的层序遍历问题
61 0
力扣429 - N叉树的层序遍历【BFS+DFS】
|
C++
【力扣·每日一题】1034. 边界着色(C++ dfs 二维vector)
【力扣·每日一题】1034. 边界着色(C++ dfs 二维vector)
73 0
【力扣·每日一题】1034. 边界着色(C++ dfs 二维vector)
|
算法
[leetcode] 2049 统计最高分的节点数目 | dfs二叉树
记录父亲节点的深度优先遍历不经常写,然后把给出的数据改成记录子节点,然后对根进行d f s dfsdfs,记录以当前节点为根的结点的数量,然后枚举删除某个节点的情况下的分数是多少{ 需要讨论当前节点是否为根 } 然后统计最大值并记录个数 Code:
91 0
[leetcode] 2049 统计最高分的节点数目 | dfs二叉树