Skip to content

Commit 0fb4dc7

Browse files
committed
动规
1 parent 1e20413 commit 0fb4dc7

3 files changed

+1467
-0
lines changed

Diff for: leetcode算法之分治法.md

+98
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
今天来盘一盘 **分治法 ** 这类题目
2+
3+
4+
5+
使用**python**刷题分类整理的笔记,请参考: [https://github.com/lxztju/leetcode-algorithm/tree/v1](https://github.com/lxztju/leetcode-algorithm/tree/v1)
6+
7+
## 分治法
8+
**分而治之**: 就是把一个复杂的问题分成两个或更多的相同或相似的子问题,直到最后子问题可以简单的直接求解,原问题的解即子问题的解的合并
9+
10+
11+
* 241 为运算表达式设计优先级 (Medium)
12+
* 95 不同的二叉搜索树 II (Medium)
13+
14+
15+
#### 241 为运算表达式设计优先级 (Medium)
16+
17+
* 以运算符为分界将计算过程分为两部分,左侧的计算结果与右侧的结果相互组合运算即可。
18+
19+
```c++
20+
class Solution {
21+
public:
22+
vector<int> diffWaysToCompute(string input) {
23+
int index = 0;
24+
int num = 0;
25+
while (index < input.size() && isdigit(input[index])){
26+
num = num* 10 + input[index] - '0';
27+
index++;
28+
}
29+
if (index == input.size())
30+
return {num};
31+
vector<int> ans;
32+
for(int i = index; i< input.size(); i++){
33+
if (input[i] == '+' || input[i] == '-' || input[i] == '*'){
34+
auto left = diffWaysToCompute(input.substr(0, i));
35+
auto right = diffWaysToCompute(input.substr(i+1));
36+
for (auto l : left){
37+
for (auto r: right){
38+
if (input[i] == '+')
39+
ans.push_back(l + r);
40+
else if (input[i] == '-')
41+
ans.push_back(l - r);
42+
else
43+
ans.push_back(l * r);
44+
}
45+
}
46+
}
47+
}
48+
return ans;
49+
}
50+
};
51+
```
52+
53+
54+
55+
#### 95 不同的二叉搜索树 II (Medium)
56+
57+
```c++
58+
class Solution {
59+
public:
60+
vector<TreeNode*> generateTrees(int n) {
61+
auto res = buildBST(1, n);
62+
return res;
63+
}
64+
vector<TreeNode*> buildBST(int left, int right){
65+
if (left > right) return {nullptr};
66+
vector<TreeNode*> trees;
67+
for (int i = left; i <= right; i++){
68+
auto leftTrees = buildBST(left, i-1);
69+
auto rightTrees = buildBST(i+1, right);
70+
for (auto l : leftTrees){
71+
for (auto r : rightTrees){
72+
TreeNode* root = new TreeNode(i);
73+
root->left = l;
74+
root->right = r;
75+
trees.push_back(root);
76+
}
77+
}
78+
}
79+
return trees;
80+
}
81+
};
82+
```
83+
84+
85+
86+
87+
88+
## 更多分类刷题资料
89+
90+
* 微信公众号: 小哲AI
91+
92+
![wechat_QRcode](https://img-blog.csdnimg.cn/20210104185413204.jpg)
93+
94+
* GitHub地址: [https://github.com/lxztju/leetcode-algorithm](https://github.com/lxztju/leetcode-algorithm)
95+
* csdn博客: [https://blog.csdn.net/lxztju](https://blog.csdn.net/lxztju)
96+
* 知乎专栏: [https://www.zhihu.com/column/c_1101089619118026752](https://www.zhihu.com/column/c_1101089619118026752)
97+
* AI研习社专栏:[https://www.yanxishe.com/column/109](https://www.yanxishe.com/column/109)
98+

0 commit comments

Comments
 (0)