【98】Validate Binary Search Tree

【99】Recover Binary Search Tree

【100】Same Tree

【101】Symmetric Tree

【104】Maximum Depth of Binary Tree

【105】Construct Binary Tree from Preorder and Inorder Traversal

【106】Construct Binary Tree from Inorder and Postorder Traversal

【108】Convert Sorted Array to Binary Search Tree

【109】Convert Sorted List to Binary Search Tree

【110】Balanced Binary Tree

【111】Minimum Depth of Binary Tree

【112】Path Sum

【113】Path Sum II

【114】Flatten Binary Tree to Linked List

【116】Populating Next Right Pointers in Each Node

【117】Populating Next Right Pointers in Each Node II

【124】Binary Tree Maximum Path Sum

【129】Sum Root to Leaf Numbers

【130】Surrounded Regions

【133】Clone Graph

【199】Binary Tree Right Side View

【200】Number of Islands

【207】Course Schedule

【210】Course Schedule II

【257】Binary Tree Paths

【261】Graph Valid Tree

【301】Remove Invalid Parentheses

【323】Number of Connected Components in an Undirected Graph

【329】Longest Increasing Path in a Matrix

【332】Reconstruct Itinerary

【337】House Robber III

【339】Nested List Weight Sum (2019年2月12日)

给了一个嵌套的list,每个元素当前的权重 = 当前的深度* 数字的大小。最外面一层深度为1,然后逐层递增。返回整个列表的权重。

 1 /**
 2  * // This is the interface that allows for creating nested lists.
 3  * // You should not implement it, or speculate about its implementation
 4  * class NestedInteger {
 5  *   public:
 6  *     // Constructor initializes an empty nested list.
 7  *     NestedInteger();
 8  *
 9  *     // Constructor initializes a single integer.
10  *     NestedInteger(int value);
11  *
12  *     // Return true if this NestedInteger holds a single integer, rather than a nested list.
13  *     bool isInteger() const;
14  *
15  *     // Return the single integer that this NestedInteger holds, if it holds a single integer
16  *     // The result is undefined if this NestedInteger holds a nested list
17  *     int getInteger() const;
18  *
19  *     // Set this NestedInteger to hold a single integer.
20  *     void setInteger(int value);
21  *
22  *     // Set this NestedInteger to hold a nested list and adds a nested integer to it.
23  *     void add(const NestedInteger &ni);
24  *
25  *     // Return the nested list that this NestedInteger holds, if it holds a nested list
26  *     // The result is undefined if this NestedInteger holds a single integer
27  *     const vector<NestedInteger> &getList() const;
28  * };
29  */
30 class Solution {
31 public:
32     int depthSum(vector<NestedInteger>& nestedList) {
33         return depthSum(nestedList, 1);
34     }
35     int depthSum(vector<NestedInteger>& nestedList, int level) {
36         int ans = 0;
37         for (int idx = 0; idx < nestedList.size(); ++ idx) {
38             if (nestedList[idx].isInteger()) {
39                 ans += nestedList[idx].getInteger() * level;
40             } else {
41                 ans += depthSum(nestedList[idx].getList(), level + 1);
42             }
43         }
44         return ans;
45     }
46 };

View Code

【364】Nested List Weight Sum II (2019年2月12日)

给了一个嵌套的list,每个元素当前的权重 = 当前的深度* 数字的大小。深度最里面一层为1,然后逐层递增。返回整个列表的权重。

题解:先计算下深度最深有多少,然后在逐层遍历。

 1 /**
 2  * // This is the interface that allows for creating nested lists.
 3  * // You should not implement it, or speculate about its implementation
 4  * class NestedInteger {
 5  *   public:
 6  *     // Constructor initializes an empty nested list.
 7  *     NestedInteger();
 8  *
 9  *     // Constructor initializes a single integer.
10  *     NestedInteger(int value);
11  *
12  *     // Return true if this NestedInteger holds a single integer, rather than a nested list.
13  *     bool isInteger() const;
14  *
15  *     // Return the single integer that this NestedInteger holds, if it holds a single integer
16  *     // The result is undefined if this NestedInteger holds a nested list
17  *     int getInteger() const;
18  *
19  *     // Set this NestedInteger to hold a single integer.
20  *     void setInteger(int value);
21  *
22  *     // Set this NestedInteger to hold a nested list and adds a nested integer to it.
23  *     void add(const NestedInteger &ni);
24  *
25  *     // Return the nested list that this NestedInteger holds, if it holds a nested list
26  *     // The result is undefined if this NestedInteger holds a single integer
27  *     const vector<NestedInteger> &getList() const;
28  * };
29  */
30 class Solution {
31 public:
32     int maxDepth = 0;
33     int depthSumInverse(vector<NestedInteger>& nestedList) {
34         getMaxDepth(nestedList, 1);
35         int curDepth = maxDepth;
36         return calRes(nestedList, curDepth);
37     }
38     void getMaxDepth(const vector<NestedInteger>& nestedList, int curDepth) {
39         maxDepth = max(maxDepth, curDepth);
40         for (auto& element : nestedList) {
41             if(!element.isInteger()) {
42                 getMaxDepth(element.getList(), curDepth + 1);
43             }
44         }
45         return;
46     }
47     int calRes(const vector<NestedInteger>& nestedList, int curDepth) {
48         int res = 0;
49         for (auto& ele : nestedList) {
50             if (ele.isInteger()) {
51                 res += ele.getInteger() * curDepth;
52             } else {
53                 res += calRes(ele.getList(), curDepth - 1);
54             }
55         }
56         return res;
57     }
58 };

View Code

【366】Find Leaves of Binary Tree

【394】Decode String

【417】Pacific Atlantic Water Flow

【430】Flatten a Multilevel Doubly Linked List

【439】Ternary Expression Parser

【472】Concatenated Words (2018年12月18日,算法群,类似题目 140)

【473】Matchsticks to Square (2019年2月23日,算法群) (M)

给了一个数组,每个数组的元素代表一根火柴棍的长度,问这些火柴棍能不能围成一个正方形。火柴棍只能拼接,不能折断。

Input: [1,1,2,2,2]
Output: trueExplanation: You can form a square with length 2, one side of the square came two sticks with length 1.

题解:dfs求解。

 1 class Solution {
 2 public:
 3     bool makesquare(vector<int>& nums) {
 4         n = nums.size();
 5         if (n == 0) {return false;}
 6         sort(nums.begin(), nums.end());
 7         int tot = 0;
 8         for (auto& num : nums) {
 9             tot += num;
10         }
11         if (tot % 4) {return false;}
12         int len = tot / 4;
13         if (nums.back() > len) {return false;}
14         vector<int> visit(n, -1);
15         return dfs(nums, visit, len, 0, 0);
16     }
17     int n;
18     bool dfs(vector<int>& nums, vector<int>& visit, const int len, int side, int curLen) {
19         if (side == 4) {return true;}
20         for (int i = n - 1; i >= 0; --i) {
21             bool res = false;
22             if (visit[i] != -1) {continue;}
23             if (curLen + nums[i] > len) {return false;}
24             visit[i] = side;
25             if (curLen + nums[i] == len) {
26                 res = dfs(nums, visit, len, side + 1, 0);
27             } else {
28                 res = dfs(nums, visit, len, side, curLen + nums[i]);
29             }
30             visit[i] = -1;
31             if (res) {return res;}
32         }
33         return false;
34     }
35 };

View Code

【488】Zuma Game

【489】Robot Room Cleaner

【490】The Maze

【491】Increasing Subsequences

【494】Target Sum

【499】The Maze III

【505】The Maze II

【513】Find Bottom Left Tree Value

【514】Freedom Trail

【515】Find Largest Value in Each Tree Row

【529】Minesweeper (2019年2月25日,微软tag)

给了一个游戏规则,输入是扫雷的当前局面,和当前想点击的坐标,返回扫雷游戏当前局面的下一个局面。

游戏规则如下:

  1. If a mine ('M') is revealed, then the game is over - change it to 'X'.
  2. If an empty square ('E') with no adjacent mines is revealed, then change it to revealed blank ('B') and all of its adjacent unrevealed squares should be revealed recursively.
  3. If an empty square ('E') with at least one adjacent mine is revealed, then change it to a digit ('1' to '8') representing the number of adjacent mines.
  4. Return the board when no more squares will be revealed.

题解:我们用dfs求解,如果是 M 或者周围有 mine 的 E 的话,就在这个位置上返回 ‘X’ 或者雷的个数。如果是周围没有 mine 的 E 的话,就把当前的位置set 成为 ’B‘,然后把dfs他的八联通的格子。

 1 class Solution {
 2 public:
 3     vector<vector<char>> updateBoard(vector<vector<char>>& board, vector<int>& click) {
 4         n = board.size(), m = board[0].size();
 5         auto res = board;
 6         dfs(res, click[0], click[1]);
 7         return res;
 8     }
 9     int n, m;
10     const int dirx[8] = {-1, -1, -1, 0, 0, 1, 1, 1};
11     const int diry[8] = {-1, 0, 1, -1, 1, -1, 0, 1};
12     void dfs(vector<vector<char>>& res, int x, int y) {
13         if (x < 0 || x >= n || y < 0 || y >= m) {return;}
14         if (res[x][y] == 'M') {
15             res[x][y] = 'X'; return;
16         }
17         if (res[x][y] == 'B') {return;}
18         int count = getAdjMine(res, x, y);
19         if (count) {
20             res[x][y] = count + '0'; return;
21         }
22         res[x][y] = 'B';
23         for (int k = 0; k < 8; ++k) {
24             int newx = dirx[k] + x, newy = diry[k] + y;
25             dfs(res, newx, newy);
26         }
27     }
28     int getAdjMine(vector<vector<char>>& res, int x, int y) {
29         int cnt = 0;
30         for (int k = 0; k < 8; ++k) {
31             int newx = dirx[k] + x, newy = diry[k] + y;
32             if (newx < 0 || newx >= n || newy < 0 || newy >= m) { continue; }
33             if (res[newx][newy] == 'M') {
34                 ++cnt;
35             }
36         }
37         return cnt;
38     }
39 };

View Code

【531】Lonely Pixel I

【533】Lonely Pixel II

【542】01 Matrix

【546】Remove Boxes

【547】Friend Circles

【559】Maximum Depth of N-ary Tree

【576】Out of Boundary Paths

【638】Shopping Offers (2018年12月24日,算法群)

有几种商品,每种商品有特定的单价,也有几种商品组合的special offer,给了一个购买清单,(每种商品买几个)。问最小花费。组合价格可以随便用很多次都可以。

Input: [2,5], [[3,0,5],[1,2,10]], [3,2]
Output: 14
Explanation:
There are two kinds of items, A and B. Their prices are $2 and $5 respectively.
In special offer 1, you can pay $5 for 3A and 0B
In special offer 2, you can pay $10 for 1A and 2B.
You need to buy 3A and 2B, so you may pay $10 for 1A and 2B (special offer #2), and $4 for 2A.

题解:dfs,商品最差是个数*单价的累加和。我们在每一层dfs中尝试用一个组合价去递归,遍历所有解集找出答案。

 1 class Solution {
 2 public:
 3     int shoppingOffers(vector<int>& price, vector<vector<int>>& special, vector<int>& needs) {
 4         n = price.size();
 5         m = special.size();
 6         vector<int> allZero(n, 0);
 7         string str = vec2str(allZero);
 8         memo[str] = 0;
 9         int ret = dfs(price, special, needs);
10         return ret;
11     }
12     int n, m;
13     unordered_map<string, int> memo;
14     inline string vec2str(const vector<int>& needs) {
15         string ret = to_string(needs[0]);
16         for (int i = 1; i < n; ++i) {
17             ret = ret + ";" + to_string(needs[i]);
18         }
19         return ret;
20     }
21     int dfs (vector<int>& price, vector<vector<int>>& special, vector<int>& needs) {
22         string strNeeds = vec2str(needs);
23         if (memo.find(strNeeds) != memo.end()) {
24             return memo[strNeeds];
25         }
26         int ret = 0;
27         for (int i = 0; i < n; ++i) {
28             ret += price[i] * needs[i];
29         }
30         for (auto& sp : special) {
31             bool canCal = true;
32             auto newNeeds = needs;
33             for (int i = 0; i < n; ++i) {
34                 if (newNeeds[i] < sp[i]) {
35                     canCal = false;
36                     break;
37                 }
38                 newNeeds[i] -= sp[i];
39             }
40             if (canCal) {
41                 ret = min(ret,  sp.back() + dfs(price, special, newNeeds));
42             }
43         }
44         memo[strNeeds] = ret;
45         return ret;
46     }
47 };

View Code

【664】Strange Printer

【679】24 Game (2019年3月11日,google tag)

给了四个数,问这四个数能不能通过 加减乘除 和 括号 得到 24。能的话返回 true,不能的话返回 false。

Example 1:
Input: [4, 1, 8, 7]
Output: True
Explanation: (8-4) * (7-1) = 24
Example 2:
Input: [1, 2, 1, 2]
Output: False
Note:
The division operator / represents real division, not integer division. For example, 4 / (1 - 2/3) = 12.
Every operation done is between two numbers. In particular, we cannot use - as a unary operator. For example, with [1, 1, 1, 1] as input, the expression -1 - 1 - 1 - 1 is not allowed.
You cannot concatenate numbers together. For example, if the input is [1, 2, 1, 2], we cannot write this as 12 + 12.

题解:dfs

 1 class Solution {
 2 public:
 3     bool judgePoint24(vector<int>& nums) {
 4         vector<double> numbers(4);
 5         for (int i = 0; i < nums.size(); ++i) {
 6             numbers[i] = (double)nums[i];
 7         }
 8         return dfs(numbers);
 9     }
10     const double EPS = 1e-6;
11     bool dfs(vector<double>& nums) {
12         if (nums.size() == 1) {
13             return abs(nums[0] -24.0) < EPS;
14         }
15         const int n = nums.size();
16         for (int i = 0; i < n; ++i) {
17             for (int j = i + 1; j < n; ++j) {
18                 vector<double> next;
19                 for (int k = 0; k < n; ++k) {
20                     if (i != k && j != k) {
21                         next.push_back(nums[k]);
22                     }
23                 }
24                 next.push_back(1.0);
25                 vector<double> candidate;
26                 const double a = nums[i], b = nums[j];
27                 candidate.push_back(a+b);
28                 candidate.push_back(a-b);
29                 candidate.push_back(b-a);
30                 candidate.push_back(a*b);
31                 if (abs(a - 0.0) > EPS) {candidate.push_back(b/a);}
32                 if (abs(b - 0.0) > EPS) {candidate.push_back(a/b);}
33                 for (auto& e : candidate) {
34                     next.back() = e;
35                     bool res = dfs(next);
36                     if (res) {return true;}
37                 }
38             }
39         }
40         return false;
41     }
42 };

View Code

【685】Redundant Connection II

【690】Employee Importance

【694】Number of Distinct Islands (2019年3月12日,google tag)

给了一个grid,上面 1 的联通区域代表一个岛屿,问一共有多少个 distinct 的岛屿。

Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.

Count the number of distinct islands. An island is considered to be the same as another if and only if one island can be translated (and not rotated or reflected) to equal the other.

Example 1:

11000
11000
00011
00011

Given the above grid map, return 1.

Example 2:

11011
10000
00001
11011

Given the above grid map, return 3.
Notice that:

11
1

and

 1
11

are considered different island shapes, because we do not consider reflection / rotation.

Note: The length of each dimension in the given grid does not exceed 50.

题解:dfs这个 grid,怎么存岛屿有两种存法,第一个是存整个岛屿所有的坐标和一开始dfs的点的offset。第二个是把岛屿encode成字符串。

第一种方法:

 1 class Solution {
 2 public:
 3     int numDistinctIslands(vector<vector<int>>& grid) {
 4         n = grid.size(), m = grid[0].size();
 5         set<vector<pair<int, int>>> st; //vector<pair<int, int>> 记录联通区域内的每一个点距离一开始遍历点的offset
 6         for (int i = 0; i < n; ++i) {
 7             for (int j = 0; j < m; ++j) {
 8                 if (grid[i][j] == 1) {
 9                     vector<pair<int, int>> offset;
10                     dfs(grid, i, j, i, j, offset);
11                     st.insert(offset);
12                 }
13             }
14         }
15         return st.size();
16     }
17     void dfs(vector<vector<int>>& grid, const int orix, const int oriy, int x, int y, vector<pair<int, int>>& offset) {
18         grid[x][y] = -1;
19         offset.push_back(make_pair(x-orix, y-oriy));
20         for (int k = 0; k < 4; ++k) {
21             int newx = x + dirx[k], newy = y + diry[k];
22             if (newx < 0 || newx >= n || newy < 0 || newy >= m || grid[newx][newy] != 1) {continue;}
23             dfs(grid, orix, oriy, newx, newy, offset);
24         }
25         return;
26     }
27     int n, m;
28     int dirx[4] = {-1, 0 ,1, 0};
29     int diry[4] = {0, -1, 0, 1};
30 };

View Code

【695】Max Area of Island

【711】Number of Distinct Islands II

【721】Accounts Merge

【733】Flood Fill

【737】Sentence Similarity II

【743】Network Delay Time

【749】Contain Virus

【753】Cracking the Safe

【756】Pyramid Transition Matrix

【778】Swim in Rising Water

【785】Is Graph Bipartite?

【802】Find Eventual Safe States

【827】Making A Large Island

【834】Sum of Distances in Tree

【839】Similar String Groups

【841】Keys and Rooms

【851】Loud and Rich

【863】All Nodes Distance K in Binary Tree

【872】Leaf-Similar Trees

【886】Possible Bipartition

【897】Increasing Order Search Tree

转载于:https://www.cnblogs.com/zhangwanying/p/9885372.html

【LeetCode】深搜DFS(共85题)相关推荐

  1. [二叉树|深搜|dfs] leetcode 404 左叶子之和

    [二叉树|深搜|dfs] leetcode 404 左叶子之和 1.题目 题目链接 计算给定二叉树的所有左叶子之和. 示例: 3/ \9 20/ \15 7在这个二叉树中,有两个左叶子,分别是 9 和 ...

  2. 深入递归、深搜dfs、回溯、剪纸学习。

    深入递归,深搜dfs,回溯,剪枝 参考于博客 一.双管齐下解递归 "逐步生成结果"类问题之数值型 自下而上的递归(递推,数学归纳,动态规划) 解决简单情况下的问题. 推广到稍复杂情 ...

  3. 题解HDU6148 Valley Numer(数位DP+深搜DFS)

    题解HDU6148 Valley Numer[数位DP+深搜DFS] 题目 解析 参考源码 题目 Description: 众所周知,度度熊非常喜欢数字. 它最近发明了一种新的数字:Valley Nu ...

  4. 2412 - 和为K ---深搜dfs剪枝

    **2412 - 和为K ---深搜dfs优化 **来源:东方博宜oj oj.czos.cn #include<bits/stdc++.h> using namespace std; co ...

  5. acwing-167. 木棒(深搜dfs+减枝)

    乔治拿来一组等长的木棒,将它们随机地砍断,使得每一节木棍的长度都不超过 50 个长度单位. 然后他又想把这些木棍恢复到为裁截前的状态,但忘记了初始时有多少木棒以及木棒的初始长度. 请你设计一个程序,帮 ...

  6. LeetCode —— 深搜水题记录

    正文之前 好长一段时间没有更新博客了,是因为放假了都是一整个白天地去学车,然后晚上看看书,做一做题就过去了,好在已经完成驾照考试,但是最近又没有研究什么技术,所以就只好拿这几天做的 LeetCode ...

  7. 深搜DFS\广搜BFS 图初步入门

    首先,不管是BFS还是DFS,由于时间和空间的局限性,它们只能解决数据量比较小的问题. 深搜,顾名思义,它从某个状态开始,不断的转移状态,直到无法转移,然后退回到上一步的状态,继续转移到其他状态,不断 ...

  8. 深搜(DFS),Image Perimeters

    题目链接:http://poj.org/problem?id=1111 解题报告: 1.这里深搜有一点要注意,对角线上的点,如果为'.',则total不应该增加,因为这不是他的边长. #include ...

  9. 算法学习笔记(六) 二叉树和图遍历—深搜 DFS 与广搜 BFS

    图的深搜与广搜 复习下二叉树.图的深搜与广搜. 从图的遍历说起.图的遍历方法有两种:深度优先遍历(Depth First Search), 广度优先遍历(Breadth First Search),其 ...

  10. 习题9-2(免费糖果)【深搜dfs】+【记忆化搜索】

    习题9-2 [UVa 10118]Free Candies(免费糖果) 题目大意: 桌上有4堆糖果,每堆有N(N<=40)颗.佳佳有个最多可以装5颗糖果的小篮子.他每次选择一堆糖果,把最顶上的一 ...

最新文章

  1. flex图表数据动态更新效果示例
  2. 打开共享文件闪退怎么解决_文件共享解决方案-随时随地共享同步访问文件
  3. php根据汉字首字母分组,利用PHP获取汉字首字母并且分组排序详解
  4. 手机天气显示服务器错误,手机天气云服务器
  5. shell编程中配置文件的使用
  6. 超级计算机预测2月有雪寒潮,干寒潮后,雪寒潮还要来?超级计算机:不确定性很大,需密切观察...
  7. Python nonlocal 与 global 关键字解析
  8. matlab在机械手臂中基础,关于MATLAB中的机械臂算法的分析和介绍
  9. 为什么程序员喜欢用dark mode深色模式
  10. 关于python的自省机制
  11. 微信小程序语音识别java_微信小程序实现语音识别功能
  12. 职场菜鸟如何更好的提升自己?
  13. 2011_STC_Minimizing Additive Distortion in Steganography using Syndrome-Trellis Codes Abstract
  14. CS5266设计TYPEC转HDMI带PD和USB3.1数据传输USB-C扩展坞方案
  15. android app防止锁屏_触控禁止!Touch Protector 锁定屏幕触控功能,避免意外操作(Android)...
  16. 用c语言实现《狼人杀》发牌系统【可自选模式】
  17. 智慧泊车建设方案 PPT
  18. 【Linux工具】使用nc命令在两台服务器之间传输大文件(无须密码等繁琐操作)
  19. html免费自学软件,想要自学绘画?这些非常棒的免费自学软件千万不要错过!...
  20. nodeJS 反向代理请求,解决跨域。

热门文章

  1. Linux LED驱动源码简析
  2. 每天一道LeetCode-----数独盘求解
  3. mybatis generator逆向工程使用
  4. latex中bibtex中引用会议和期刊论文时的写法及规则
  5. linux下常用的关机命令有:shutdown、halt、poweroff、init;重启命令有:reboot。下面本文就主要介绍一些常用的关机命令以及各种关机命令之间的区别和具体用法。
  6. linux dns 攻击,DNSlog攻击技巧 | CN-SEC 中文网
  7. php 目录限制,限定某个目录禁止解析php,限制user_agent,php相关配置
  8. php server 域名,php 关于如何获取域名或者IP地址的$_SERVER['']
  9. 关于递归三要素的理解
  10. Shell——常用工具(cut、sed、awk、sort)