mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 11:34:46 +08:00
Update
This commit is contained in:
@ -89,7 +89,7 @@ void backtracking(int n, int row, vector<string>& chessboard) {
|
||||
* 递归终止条件
|
||||
|
||||
在如下树形结构中:
|
||||

|
||||

|
||||
|
||||
可以看出,当递归到棋盘最底层(也就是叶子节点)的时候,就可以收集结果并返回了。
|
||||
|
||||
|
@ -36,7 +36,8 @@ n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并
|
||||
class Solution {
|
||||
private:
|
||||
int count = 0;
|
||||
void backtracking(int n, int row, vector<string>& chessboard, vector<vector<string>>& result) {
|
||||
vector<vector<string>> result;
|
||||
void backtracking(int n, int row, vector<string>& chessboard) {
|
||||
if (row == n) {
|
||||
count++;
|
||||
return;
|
||||
@ -44,7 +45,7 @@ void backtracking(int n, int row, vector<string>& chessboard, vector<vector<stri
|
||||
for (int col = 0; col < n; col++) {
|
||||
if (isValid(row, col, chessboard, n)) {
|
||||
chessboard[row][col] = 'Q'; // 放置皇后
|
||||
backtracking(n, row + 1, chessboard, result);
|
||||
backtracking(n, row + 1, chessboard);
|
||||
chessboard[row][col] = '.'; // 回溯
|
||||
}
|
||||
}
|
||||
@ -74,9 +75,10 @@ bool isValid(int row, int col, vector<string>& chessboard, int n) {
|
||||
|
||||
public:
|
||||
int totalNQueens(int n) {
|
||||
result.clear();
|
||||
std::vector<std::string> chessboard(n, std::string(n, '.'));
|
||||
vector<vector<string>> result;
|
||||
backtracking(n, 0, chessboard, result);
|
||||
backtracking(n, 0, chessboard);
|
||||
return count;
|
||||
|
||||
}
|
||||
|
@ -11,7 +11,7 @@
|
||||
|
||||
代码如下:
|
||||
|
||||
```
|
||||
```C++
|
||||
// 从前向后
|
||||
for (int i = 1; i < ratings.size(); i++) {
|
||||
if (ratings[i] > ratings[i - 1]) candyVec[i] = candyVec[i - 1] + 1;
|
||||
@ -37,7 +37,7 @@ for (int i = 1; i < ratings.size(); i++) {
|
||||
|
||||
所以代码如下:
|
||||
|
||||
```
|
||||
```C++
|
||||
// 从后向前
|
||||
for (int i = ratings.size() - 2; i >= 0; i--) {
|
||||
if (ratings[i] > ratings[i + 1] ) {
|
||||
@ -46,21 +46,8 @@ for (int i = ratings.size() - 2; i >= 0; i--) {
|
||||
}
|
||||
```
|
||||
|
||||
* 将问题分解为若干个子问题
|
||||
* 找出适合的贪心策略
|
||||
* 求解每一个子问题的最优解
|
||||
* 将局部最优解堆叠成全局最优解
|
||||
|
||||
* 分解为子问题
|
||||
|
||||
|
||||
|
||||
这道题目上来也是没什么思路啊
|
||||
|
||||
|
||||
这道题目不好想啊,贪心很巧妙
|
||||
|
||||
```
|
||||
整体代码如下:
|
||||
```C++
|
||||
class Solution {
|
||||
public:
|
||||
int candy(vector<int>& ratings) {
|
||||
@ -81,5 +68,9 @@ public:
|
||||
return result;
|
||||
}
|
||||
};
|
||||
|
||||
```
|
||||
|
||||
> **我是[程序员Carl](https://github.com/youngyangyang04),[组队刷题](https://img-blog.csdnimg.cn/20201115103410182.png)可以找我,本文[leetcode刷题攻略](https://github.com/youngyangyang04/leetcode-master)已收录,更多[精彩算法文章](https://mp.weixin.qq.com/mp/appmsgalbum?__biz=MzUxNjY5NTYxNA==&action=getalbum&album_id=1485825793120387074&scene=173#wechat_redirect)尽在:[代码随想录](https://img-blog.csdnimg.cn/20200815195519696.png),关注后就会发现和「代码随想录」相见恨晚!**
|
||||
|
||||
**如果感觉题解对你有帮助,不要吝啬给一个👍吧!**
|
||||
|
||||
|
Reference in New Issue
Block a user