# 2. 除数博弈

dp[i] = true, if i % j == 0 && dp[i - j] == fasle, j = 1, 2, ..., i - 1
dp[i] = false, else

``````class Solution {
public:
bool divisorGame(int N) {
bool win[N + 10];
win[1] = false, win[2] = true;
for (int i = 3; i <= N; i++){
int j;
for (j = 1; j < i; j++){
if (i % j == 0 && !win[i - j]){
win[i] = true;
break;
}
}
if (j == i)
win[i] = false;
}
return win[N];
}
};
``````

# 3. 节点与其祖先之间的最大差值

``````/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> path, vals;
int MAX = 0;
int maxAncestorDiff(TreeNode* root) {
path.clear();
MAX = 0;
path.push_back(root -> val);
DFS(root);
return MAX;
}

void DFS(TreeNode* root){
if (root -> left == NULL && root -> right == NULL){
vals = path; // 注意不能sort(path)，path在DFS不能被sort
sort(vals.begin(), vals.end());
int sub = vals[vals.size() - 1] - vals[0];
if (sub > MAX){
MAX = sub;
}
return ;
}

if (root -> left){
path.push_back(root -> left -> val);
DFS(root -> left);
path.pop_back();
}
if (root -> right){
path.push_back(root -> right -> val);
DFS(root -> right);
path.pop_back();
}
}
};
``````

# 4. 最长等差数列

dp[i][A[i] - A[j]] = max(dp[i][A[i] - A[j]], dp[j][A[i] - A[j]] + 1), j=0,1,2,...,i-1

``````class Solution {
public:
int longestArithSeqLength(vector<int>& A) {
vector< map<int, int> > dp(A.size());
for (int i = 0; i < A.size(); i++){
for (int j = i + 1; j < A.size(); j++){
dp[i][A[j] - A[i]] = 1; // 公差计算：后面减前面的
}
}
int MAX = 1;
for (int i = 1; i < A.size(); i++){
for (int j = 0; j < i; j++){
// 注意：公差的计算是后面的减前面的，因此是A[i]-A[j]
dp[i][A[i] - A[j]] = max(dp[i][A[i] - A[j]], dp[j][A[i] - A[j]] + 1);
MAX = max(dp[i][A[i] - A[j]], MAX);
}
}
return MAX;
}
};
``````

# 5. 从先序遍历还原二叉树（复习二叉树的重构）

``````/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int pos = 0; //记录当前遍历到的位置，总指针
string T;
int x = 0;
for (; p < T.length() && isdigit(T[p]); ++ p)
x = (x * 10) + (T[p] - '0');
return x;
}
TreeNode* Dfs(int dep) {
int cur = 0; //记录 '-' 的个数，表示下一个节点的深度
for (int j = pos; j < T.length() && T[j] == '-'; ++ j) ++ cur;
if (cur != dep) return NULL;
pos += cur;