classNode2{public:Node2(int val){
left =nullptr;
right =nullptr;this->val = val;}
Node2* left;
Node2* right;int val;};
1.给定一个非负整数n,代表二叉树的节点个数,返回能形成多少种不同的二叉树结构
inttest02(int n){if(n <0)return0;if(n <=1)return1;if(n ==2)return2;int res =0;for(int i =0; i < n -1; i++){int leftNum =test02(i);int right =test02(n -1- i);
res += leftNum * right;}return res;}
2.完整的字符串需要添加的字符
inttest03(string& s){int count =0;int ans =0;for(int i =0; i < s.size(); i++){if(s[i]=='('){
count++;}else{if(count ==0){
ans++;}else{
count--;}}}return count + ans;}
inttest06(string& s){if(s.size()==0)return0;int count =0;int res =0;for(int i =0; i < s.size(); i++){if(s[i]=='('){
count++;}else{
count--;}
res =max(count, res);}return res;}
inttest07(string& s){if(s.size()==0)return0;
vector<int>dp(s.size());int pre =0, res =0;for(int i =1; i < s.size(); i++){if(s[i]==')'){
pre = i - dp[i -1]-1;if(pre >=0&& s[pre]=='('){
dp[i]= dp[i -1]+2+(pre >0? dp[pre -1]:0);}}
res =max(res, dp[i]);}return res;}
7.给定一个栈 按升序进行排序 最多只能使用一个额外的栈存放临时数据
voidtest08(stack<int>& s){
stack<int> sta;while(!s.empty()){int top = s.top();
s.pop();if(sta.empty()|| top < sta.top()){
sta.push(top);}else{while(top < sta.top()){int tmp = sta.top();
sta.pop();
s.push(tmp);}
sta.push(top);}}
s = sta;}
inttest09_1(string s,int n){if(n == s.size()){return1;}if(s[n]=='0'){return0;}int res =test09_1(s, n +1);if(n == s.size()-1){return res;}if(((s[n]-'0')*10+ s[n +1]-'0')<27){
res +=test09_1(s, n +2);}return res;}
9.二叉树每个节点都有一个权重,求一颗二叉树从根到叶子的所有路径中权重和最大的一条路
int max10 = INT_MIN;voidtest10(Node2* head,int pre){if(head->left ==nullptr&& head->right ==nullptr){
max10 =max(max10, pre + head->val);}if(head->left){test10(head->left, pre + head->val);}if(head->right){test10(head->right, pre + head->val);}}
10.查找二维数组中的一个数字,该二维数组中数字每行每列都是有序的从小到大
booltest11(vector<vector<int>> vec,int num){int left =0;int right = vec[0].size();while(left < vec.size()&& right >=0){if(vec[left][right]== num)returntrue;if(vec[left][right]> num){
right--;}else{++left;}}returnfalse;}