96. Unique Binary Search Trees
class Solution {
public:
int numTrees(int n) {
if(n <= 2) return n;
vector<int> dp(n+1);
dp[0] = 1;
dp[1] = 1;
dp[2] = 2;
for(int i=3; i<=n; i++){
for(int j=1; j<=i; j++){
dp[i] += dp[j-1]*dp[i-j];
}
}
return dp[n];
}
};
416. Partition Equal Subset Sum
class Solution {
public:
bool canPartition(vector<int>& nums) {
int sum = 0;
for(int num:nums) sum += num;
vector<int> dp(10001, 0);
if(sum%2 == 1) return false;
int target = sum/2;
for(int i=0; i<nums.size(); i++){
for(int j=target; j>=nums[i]; j--){
dp[j] = max(dp[j], dp[j-nums[i]]+nums[i]);
}
}
if(dp[target] == target) return true;
return false;
}
};
1049. Last Stone Weight II
本质为找出总和的最相近的两堆
class Solution {
public:
int lastStoneWeightII(vector<int>& stones) {
int sum=0;
for(int stone:stones) sum += stone;
int target = sum/2;
vector<int> dp(15001, 0);
for(int i=0; i<stones.size(); i++){
for(int j=target; j >= stones[i]; j--){
dp[j] = max(dp[j], dp[j-stones[i]]+stones[i]);
}
}
int res = sum - dp[target]-dp[target];
return res;
}
};
494. Target Sum
有多少种方法把背包装满
class Solution {
public:
int findTargetSumWays(vector<int>& nums, int target) {
int sum = 0;
for(int num:nums) sum += num;
if((target+sum)%2 == 1) return 0;
if(abs(target) > sum) return 0;
int bagsize = (target+sum)/2;
vector<int> dp(bagsize+1, 0);
dp[0] = 1;
for(int i=0; i<nums.size(); i++){
for(int j=bagsize; j>=nums[i]; j--){
dp[j] += dp[j-nums[i]];
}
}
return dp[bagsize];
}
};