【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,然后逐层递增。返回整个列表的权重。

 /**
* // This is the interface that allows for creating nested lists.
* // You should not implement it, or speculate about its implementation
* class NestedInteger {
* public:
* // Constructor initializes an empty nested list.
* NestedInteger();
*
* // Constructor initializes a single integer.
* NestedInteger(int value);
*
* // Return true if this NestedInteger holds a single integer, rather than a nested list.
* bool isInteger() const;
*
* // Return the single integer that this NestedInteger holds, if it holds a single integer
* // The result is undefined if this NestedInteger holds a nested list
* int getInteger() const;
*
* // Set this NestedInteger to hold a single integer.
* void setInteger(int value);
*
* // Set this NestedInteger to hold a nested list and adds a nested integer to it.
* void add(const NestedInteger &ni);
*
* // Return the nested list that this NestedInteger holds, if it holds a nested list
* // The result is undefined if this NestedInteger holds a single integer
* const vector<NestedInteger> &getList() const;
* };
*/
class Solution {
public:
int depthSum(vector<NestedInteger>& nestedList) {
return depthSum(nestedList, );
}
int depthSum(vector<NestedInteger>& nestedList, int level) {
int ans = ;
for (int idx = ; idx < nestedList.size(); ++ idx) {
if (nestedList[idx].isInteger()) {
ans += nestedList[idx].getInteger() * level;
} else {
ans += depthSum(nestedList[idx].getList(), level + );
}
}
return ans;
}
};

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

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

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

 /**
* // This is the interface that allows for creating nested lists.
* // You should not implement it, or speculate about its implementation
* class NestedInteger {
* public:
* // Constructor initializes an empty nested list.
* NestedInteger();
*
* // Constructor initializes a single integer.
* NestedInteger(int value);
*
* // Return true if this NestedInteger holds a single integer, rather than a nested list.
* bool isInteger() const;
*
* // Return the single integer that this NestedInteger holds, if it holds a single integer
* // The result is undefined if this NestedInteger holds a nested list
* int getInteger() const;
*
* // Set this NestedInteger to hold a single integer.
* void setInteger(int value);
*
* // Set this NestedInteger to hold a nested list and adds a nested integer to it.
* void add(const NestedInteger &ni);
*
* // Return the nested list that this NestedInteger holds, if it holds a nested list
* // The result is undefined if this NestedInteger holds a single integer
* const vector<NestedInteger> &getList() const;
* };
*/
class Solution {
public:
int maxDepth = ;
int depthSumInverse(vector<NestedInteger>& nestedList) {
getMaxDepth(nestedList, );
int curDepth = maxDepth;
return calRes(nestedList, curDepth);
}
void getMaxDepth(const vector<NestedInteger>& nestedList, int curDepth) {
maxDepth = max(maxDepth, curDepth);
for (auto& element : nestedList) {
if(!element.isInteger()) {
getMaxDepth(element.getList(), curDepth + );
}
}
return;
}
int calRes(const vector<NestedInteger>& nestedList, int curDepth) {
int res = ;
for (auto& ele : nestedList) {
if (ele.isInteger()) {
res += ele.getInteger() * curDepth;
} else {
res += calRes(ele.getList(), curDepth - );
}
}
return res;
}
};

【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: true Explanation: You can form a square with length 2, one side of the square came two sticks with length 1.

题解:dfs求解。

 class Solution {
public:
bool makesquare(vector<int>& nums) {
n = nums.size();
if (n == ) {return false;}
sort(nums.begin(), nums.end());
int tot = ;
for (auto& num : nums) {
tot += num;
}
if (tot % ) {return false;}
int len = tot / ;
if (nums.back() > len) {return false;}
vector<int> visit(n, -);
return dfs(nums, visit, len, , );
}
int n;
bool dfs(vector<int>& nums, vector<int>& visit, const int len, int side, int curLen) {
if (side == ) {return true;}
for (int i = n - ; i >= ; --i) {
bool res = false;
if (visit[i] != -) {continue;}
if (curLen + nums[i] > len) {return false;}
visit[i] = side;
if (curLen + nums[i] == len) {
res = dfs(nums, visit, len, side + , );
} else {
res = dfs(nums, visit, len, side, curLen + nums[i]);
}
visit[i] = -;
if (res) {return res;}
}
return false;
}
};

【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他的八联通的格子。

 class Solution {
public:
vector<vector<char>> updateBoard(vector<vector<char>>& board, vector<int>& click) {
n = board.size(), m = board[].size();
auto res = board;
dfs(res, click[], click[]);
return res;
}
int n, m;
const int dirx[] = {-, -, -, , , , , };
const int diry[] = {-, , , -, , -, , };
void dfs(vector<vector<char>>& res, int x, int y) {
if (x < || x >= n || y < || y >= m) {return;}
if (res[x][y] == 'M') {
res[x][y] = 'X'; return;
}
if (res[x][y] == 'B') {return;}
int count = getAdjMine(res, x, y);
if (count) {
res[x][y] = count + ''; return;
}
res[x][y] = 'B';
for (int k = ; k < ; ++k) {
int newx = dirx[k] + x, newy = diry[k] + y;
dfs(res, newx, newy);
}
}
int getAdjMine(vector<vector<char>>& res, int x, int y) {
int cnt = ;
for (int k = ; k < ; ++k) {
int newx = dirx[k] + x, newy = diry[k] + y;
if (newx < || newx >= n || newy < || newy >= m) { continue; }
if (res[newx][newy] == 'M') {
++cnt;
}
}
return cnt;
}
};

【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中尝试用一个组合价去递归,遍历所有解集找出答案。

 class Solution {
public:
int shoppingOffers(vector<int>& price, vector<vector<int>>& special, vector<int>& needs) {
n = price.size();
m = special.size();
vector<int> allZero(n, );
string str = vec2str(allZero);
memo[str] = ;
int ret = dfs(price, special, needs);
return ret;
}
int n, m;
unordered_map<string, int> memo;
inline string vec2str(const vector<int>& needs) {
string ret = to_string(needs[]);
for (int i = ; i < n; ++i) {
ret = ret + ";" + to_string(needs[i]);
}
return ret;
}
int dfs (vector<int>& price, vector<vector<int>>& special, vector<int>& needs) {
string strNeeds = vec2str(needs);
if (memo.find(strNeeds) != memo.end()) {
return memo[strNeeds];
}
int ret = ;
for (int i = ; i < n; ++i) {
ret += price[i] * needs[i];
}
for (auto& sp : special) {
bool canCal = true;
auto newNeeds = needs;
for (int i = ; i < n; ++i) {
if (newNeeds[i] < sp[i]) {
canCal = false;
break;
}
newNeeds[i] -= sp[i];
}
if (canCal) {
ret = min(ret, sp.back() + dfs(price, special, newNeeds));
}
}
memo[strNeeds] = ret;
return ret;
}
};

【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

 class Solution {
public:
bool judgePoint24(vector<int>& nums) {
vector<double> numbers();
for (int i = ; i < nums.size(); ++i) {
numbers[i] = (double)nums[i];
}
return dfs(numbers);
}
const double EPS = 1e-;
bool dfs(vector<double>& nums) {
if (nums.size() == ) {
return abs(nums[] -24.0) < EPS;
}
const int n = nums.size();
for (int i = ; i < n; ++i) {
for (int j = i + ; j < n; ++j) {
vector<double> next;
for (int k = ; k < n; ++k) {
if (i != k && j != k) {
next.push_back(nums[k]);
}
}
next.push_back(1.0);
vector<double> candidate;
const double a = nums[i], b = nums[j];
candidate.push_back(a+b);
candidate.push_back(a-b);
candidate.push_back(b-a);
candidate.push_back(a*b);
if (abs(a - 0.0) > EPS) {candidate.push_back(b/a);}
if (abs(b - 0.0) > EPS) {candidate.push_back(a/b);}
for (auto& e : candidate) {
next.back() = e;
bool res = dfs(next);
if (res) {return true;}
}
}
}
return false;
}
};

【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成字符串。

第一种方法:

 class Solution {
public:
int numDistinctIslands(vector<vector<int>>& grid) {
n = grid.size(), m = grid[].size();
set<vector<pair<int, int>>> st; //vector<pair<int, int>> 记录联通区域内的每一个点距离一开始遍历点的offset
for (int i = ; i < n; ++i) {
for (int j = ; j < m; ++j) {
if (grid[i][j] == ) {
vector<pair<int, int>> offset;
dfs(grid, i, j, i, j, offset);
st.insert(offset);
}
}
}
return st.size();
}
void dfs(vector<vector<int>>& grid, const int orix, const int oriy, int x, int y, vector<pair<int, int>>& offset) {
grid[x][y] = -;
offset.push_back(make_pair(x-orix, y-oriy));
for (int k = ; k < ; ++k) {
int newx = x + dirx[k], newy = y + diry[k];
if (newx < || newx >= n || newy < || newy >= m || grid[newx][newy] != ) {continue;}
dfs(grid, orix, oriy, newx, newy, offset);
}
return;
}
int n, m;
int dirx[] = {-, ,, };
int diry[] = {, -, , };
};

【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

【LeetCode】深搜DFS(共85题)的更多相关文章

  1. 图的遍历 之 深搜dfs

    DFS 遍历 深度优先搜索是一个递归过程,有回退过程. 对一个无向连通图,在访问图中某一起始顶点u 后,由u 出发,访问它的某一邻接顶点v1:再从v1 出发,访问与v1 邻接但还没有访问过的顶点v2: ...

  2. HDU 2553 N皇后问题(深搜DFS)

    N皇后问题 Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Submi ...

  3. 深搜(DFS),Image Perimeters

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

  4. 深搜(DFS),回溯,Fire Net

    题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=2 解题报告: 这里的深搜有一点不同,就是,在深搜每一个点时,都要深搜每 ...

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

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

  6. 【深搜(DFS)-例题-踏青】-C++

    描述 小白和他的朋友周末相约去召唤师峡谷踏青.他们发现召唤师峡谷的地图是由一块一块格子组成的,有的格子上是草丛,有的是空地.草丛通过上下左右 4 个方向扩展其他草丛形成一片草地,任何一片草地中的格子都 ...

  7. 【LeetCode】数学(共106题)

    [2]Add Two Numbers (2018年12月23日,review) 链表的高精度加法. 题解:链表专题:https://www.cnblogs.com/zhangwanying/p/979 ...

  8. 【LeetCode】树(共94题)

    [94]Binary Tree Inorder Traversal [95]Unique Binary Search Trees II (2018年11月14日,算法群) 给了一个 n,返回结点是 1 ...

  9. 【LeetCode】BFS(共43题)

    [101]Symmetric Tree 判断一棵树是不是对称. 题解:直接递归判断了,感觉和bfs没有什么强联系,当然如果你一定要用queue改写的话,勉强也能算bfs. // 这个题目的重点是 比较 ...

随机推荐

  1. Test 6.29 T4 简单数据结构练习

    问题描述 费了一番功夫,神犇 CJK 终于完成了前三道题目."不错,不愧是新一代神犇啊!" JesseLiu 满意地说道,"不过,你在算法方面的功底固然不错.对于数据结构 ...

  2. hdu 4641K-string SAM的O(n^2)算法 以及 SAM+并查集优化

    转载:http://www.cnblogs.com/hxer/p/5675149.html 题意:有一个长度为n(n < 5e4)的字符串,Q(Q<=2e5)次操作:操作分为:在末尾插入一 ...

  3. [NOIP2016][luogu]换教室[DP]

    [NOIP2016] Day1 T3 换教室 ——!x^n+y^n=z^n 题目描述 对于刚上大学的牛牛来说,他面临的第一个问题是如何根据实际情况申请合适的课程. 在可以选择的课程中,有 2n 节课程 ...

  4. FFT IP核调用与仿真之FFT数学分析

    对于FFT这个IP核,我其实对它真的是又爱又恨,因为它真的耗费了我太多时间,但是随着研究的深入,遇到的问题一点点给消化解决,终于不用带着问题睡觉了,哈哈,有时候真的挺佩服自己的,遇到不懂的,不了解的, ...

  5. 修改Oracle数据库SGA和PGA大小

    SGA的大小:一般物理内存20%用作操作系统保留,其他80%用于数据库.SGA普通数据库可以分配40%-60%之间,PGA可以分配20%-40%之间.1.以dba身份登录并查看SGA信息:SQL> ...

  6. spring+JdbcTemplate简单使用(一)

    目录 @ 1. 环境配置 maven(项目管理) idea(编译器) jdk1.8(Java环境) MySQL5.6(MySQL数据库) 2. 创建项目 在 idea 中创建普通的 maven 项目 ...

  7. Scala从入门到放弃(三)Scala的数组、映射、元组和集合

    1.数组 1.1定长数组和变长数组 object ArrayDemo { def main(args: Array[String]): Unit = { //初始化一个长度为8的定长数组,其数组元素均 ...

  8. 一文读懂PID控制算法(抛弃公式,从原理上真正理解PID控制)

      PID控制应该算是应用非常广泛的控制算法了.小到控制一个元件的温度,大到控制无人机的飞行姿态和飞行速度等等,都可以使用PID控制.这里我们从原理上来理解PID控制. PID(proportion ...

  9. h5分线程Worker

    <!DOCTYPE html><html><head> <meta charset="UTF-8"> <title>Ti ...

  10. CSS-格式化上下文(Formatting Context)

    Formatting Context:指页面中的一个渲染区域,并且拥有一套渲染规则,他决定了其子元素如何定位,以及与其他元素的相互关系和作用. BFC 块级格式化上下文,它是指一个独立的块级渲染区域, ...