Skip to content

Commit 076bee4

Browse files
committed
week3作业提交
1 parent 7df7190 commit 076bee4

3 files changed

Lines changed: 64 additions & 1 deletion

File tree

Week03/NOTE.md

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,6 @@
1-
学习笔记
1+
学习笔记
2+
1.主要学习了递归,记住递归的模板。 1.terminator 2.process 3.drill down 4.reverse
3+
2.回溯、分治也是,相当于递归的变种。
4+
3.对于回溯的了解还是有点不到位,需要反复复习及练习题去了解。
5+
4.分治其实还好,最初了解分治思想是通过归并排序(我认为是最好理解的排序算法之一)。
6+
5.还是需要熟练的使用递归。
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8+
* };
9+
*/
10+
class Solution {
11+
public:
12+
TreeNode *answer;
13+
//深度遍历
14+
bool dfs(TreeNode* root,TreeNode* p,TreeNode* q){
15+
//terminator
16+
if(root == nullptr)
17+
return false;
18+
//process
19+
20+
//drill down
21+
bool lson = dfs(root->left,p,q);
22+
bool rson = dfs(root->right,p,q);
23+
if((lson && rson) ||( (root->val == p->val || root->val == q->val) && (lson || rson)) )
24+
{
25+
answer = root;
26+
}
27+
return lson || rson || (p->val == root->val || q->val == root->val);
28+
}
29+
30+
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
31+
dfs(root,p,q);
32+
return answer;
33+
}
34+
};

Week03/permutations.cpp

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
class Solution {
2+
public:
3+
void backtrack(std::vector<std::vector<int>>& result, std::vector<int>& output, int index, int len){
4+
//terminator
5+
if (index == len) {
6+
result.push_back(output);
7+
return;
8+
}
9+
//process
10+
for (int i = index; i < len; ++i) {
11+
swap(output[i], output[index]);
12+
//drill down
13+
backtrack(result, output, index + 1, len);
14+
//reverse
15+
swap(output[i], output[index]);
16+
}
17+
}
18+
vector<vector<int>> permute(vector<int>& nums) {
19+
std::vector<vector<int> > result;
20+
int n = nums.size();
21+
backtrack(result, nums, 0, n);
22+
return result;
23+
}
24+
};

0 commit comments

Comments
 (0)