- DP[i][j] = DP[i - 1][j] + DP[i][j - c[i]]
假设背包体积为V,物品数为n,时间复杂度O(V * n),空间复杂度O(V),代码如下:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int findTargetSumWays(vector<int>& nums, int S) { | |
int sum = 0; | |
for(auto& num : nums) | |
sum += num; | |
int diff = sum - S; | |
if(diff < 0 || diff % 2)return 0; | |
return knapsack(nums, diff / 2); | |
} | |
private: | |
int knapsack(vector<int>& nums, int target) | |
{ | |
int len = nums.size(); | |
vector<int> dp(target + 1, 0); | |
dp[0] = 1; | |
for(int i = 0; i < len; ++i) | |
{ | |
int num = nums[i]; | |
for(int j = target; j >= num; --j) | |
{ | |
dp[j] += dp[j - num]; | |
} | |
} | |
return dp[target]; | |
} | |
}; |
No comments:
Post a Comment