96. Unique Binary Search Trees
Medium
254295Add to ListShare
Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?
Example:
Input: 3 Output: 5 Explanation: Given n = 3, there are a total of 5 unique BST's: 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3
class Solution {
public:
int numTrees(int n) {
if(n==1) return 1;
if(n==2) return 2;
vector<int> dp(n+1);
dp[0]=1;dp[1]=1;dp[2]=2;
for(int i=3;i<=n;i++){
for(int j=0;j<i;j++){
dp[i]+=dp[j]*dp[i-j-1];
}
}
return dp[n];
}
};
95. Unique Binary Search Trees II
Medium
1738139Add to ListShare
Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1 ... n.
Example:
Input: 3 Output: [ [1,null,3,2], [3,2,null,1], [3,1,null,null,2], [2,1,3], [1,null,2,null,3] ] Explanation: The above output corresponds to the 5 unique BST's shown below: 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 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<TreeNode*> helper(int a,int b,vector<vector<vector<TreeNode*> > > memo){
if(b<a) return {NULL};
if(!memo[a-1][b-1].empty()) return memo[a-1][b-1];
vector<TreeNode*> res;
for(int i=a;i<=b;i++){
vector<TreeNode*> left=helper(a,i-1,memo);
vector<TreeNode*> right=helper(i+1,b,memo);
for(int j=0;j<left.size();j++){
for(int k=0;k<right.size();k++){
TreeNode* tmp=(TreeNode*)malloc(sizeof(TreeNode));
tmp->val=i;
tmp->left=left[j];
tmp->right=right[k];
res.push_back(tmp);
}
}
}
memo[a-1][b-1]=res;
return res;
}
vector<TreeNode*> generateTrees(int n) {
if(n==0) return {};
vector<vector<vector<TreeNode*> > > memo(n,vector<vector<TreeNode*>>(n));
return helper(1,n,memo);
}
};
241. Different Ways to Add Parentheses
Medium
134066Add to ListShare
Given a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are +
, -
and *
.
Example 1:
Input:"2-1-1"
Output:[0, 2]
Explanation: ((2-1)-1) = 0 (2-(1-1)) = 2
Example 2:
Input:"2*3-4*5"
Output:[-34, -14, -10, -10, 10]
Explanation: (2*(3-(4*5))) = -34 ((2*3)-(4*5)) = -14 ((2*(3-4))*5) = -10 (2*((3-4)*5)) = -10 (((2*3)-4)*5) = 10
class Solution {
public:
vector<int> diffWaysToCompute(string input) {
vector<int> res;
for(int i=0;i<input.size();i++){
if(input[i]=='+' || input[i]=='-' || input[i]=='*'){
vector<int> left=diffWaysToCompute(input.substr(0,i));
vector<int> right=diffWaysToCompute(input.substr(i+1));
for(int j=0;j<left.size();j++){
for(int k=0;k<right.size();k++){
if(input[i]=='+') res.push_back(left[j]+right[k]);
else if(input[i]=='-') res.push_back(left[j]-right[k]);
else if(input[i]=='*') res.push_back(left[j]*right[k]);
}
}
}
}
if(res.empty()) res.push_back(stoi(input));
return res;
}
};