96. Unique Binary Search Trees
原题:
Given n, how many structurally unique BST’s (binary search trees) that store values 1…n?
For example,
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
题解:
给定一个正整数n,问数字1~n可以构成多少棵不同的二叉搜索树。
首先要知道二叉搜索树的特性,就是每个节点的左子树中的所有元素都比它小,右子树中的节点都比它大。而且两个子树都是二叉搜索树。那么可以这样说。在1~n数字中,如果数字i
作为根节点,那么根节点的左子树一定是由1 ~ i-1
构成,右子树一定是i+1 ~ n
。在这种情况下,i+1 ~ n
中的数字可以整体减去i,变成1 ~ n-i
的情况。很明显就是DP的状态转移了。
因此用f(n)
表示n个数字有多少种不同的二叉搜索树,有:
# python表示
f(0) = f(1) = 1
f(n) = sum([f(i-1)*f(n-i) for i in range(1, n+1)])
代码:
class Solution {
public:
int numTrees(int n) {
if(n<2) {
return 1;
}
vector<int> f(n+1);
f[0] = 1;
f[1] = 1;
for(int i=1; i<=n; i++) {
f[i] = 0;
for(int j=1; j<=i; j++) {
f[i] += f[j-1] * f[i-j];
}
}
return f[n];
}
};
416. Partition Equal Subset Sum
原题:
Given a non-empty array containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.
Note:
Each of the array element will not exceed 100.
The array size will not exceed 200.
Example 1:
Input: [1, 5, 11, 5]
Output: true
Explanation: The array can be partitioned as [1, 5, 5] and [11].
Example 2:
Input: [1, 2, 3, 5]
Output: false
Explanation: The array cannot be partitioned into equal sum subsets.
题解:
给一组正整数,问能否把它们分成两个子集,使得两个集合的和相等。
首先可以排除一个明显无解的情况:数组的和为奇数。
把数组和除于二后,得到一个subsum
,于是把问题变成了subset sum
问题。
subset sum
问题有伪多项式的解法,用f(i, j)
表示0到i个元素能否找到子集的和为j。
状态转移式为:
f(i, j) = (i == j) || (f(i-1, j)) || (j-i>=0 && f(i-1, j-i))
代码:
class Solution {
public:
bool canPartition(vector<int>& nums) {
int sum = 0;
for(auto x: nums) {
sum += x;
}
if(sum % 2) {
return false;
}
sum /= 2;
vector<vector<bool>> f(nums.size(), vector<bool>(sum+1));
// f[0][sum] = (nums[0] == sum);
for(int j=1; j<=sum; ++j) {
f[0][j] = (nums[0] == j);
}
for(int i=1; i<nums.size(); ++i) {
for(int j=1; j<=sum; ++j) {
f[i][j] = (nums[i] == j) || (f[i-1][j]) || (j-nums[i]>=0 && f[i-1][j-nums[i]]);
}
}
return f[nums.size()-1][sum];
}
};