You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symbols +
and -
. For each integer, you should choose one from +
and -
as its new symbol.
Find out how many ways to assign symbols to make sum of integers equal to target S.
Example 1:
Input: nums is [1, 1, 1, 1, 1], S is 3. Output: 5 Explanation: -1+1+1+1+1 = 3 +1-1+1+1+1 = 3 +1+1-1+1+1 = 3 +1+1+1-1+1 = 3 +1+1+1+1-1 = 3 There are 5 ways to assign symbols to make the sum of nums be target 3.
我的思路:
(1)写出递归函数:
class Solution { public: int findTargetSumWays(vector<int>& nums, int S) { return doDp(nums,nums.size()-1,S); } int doDp(vector<int>& nums,int i,int S){ if(i==0) { if(nums[i]==S||nums[i]==-S) return 1; } return doDp(nums,i-1,S-nums[i])+doDp(nums,i-1,S+nums[i]); } };
参考答案:
注意这种加和变动的情况,虽然遍历的时候是从左daoyou,但是实际上的第二个下标值是跳跃变动的
class Solution { public: int findTargetSumWays(vector<int>& nums, int S) { vector<vector<int>> dp(nums.size(),vector<int>(2001,0)); dp[0][nums[0]+1000]=1; dp[0][-nums[0]+1000]+=1;//如果nums[0]为0,正负号都可以 for(int i=1;i<nums.size();i++) for(int sum=-1000;sum<=1000;sum++) { if(dp[i-1][sum+1000]>0) { dp[i][sum+nums[i]+1000] +=dp[i-1][sum+1000];//注意这里的+= dp[i][sum-nums[i]+1000]+=dp[i-1][sum+1000]; } } return S>1000?0:dp[nums.size()-1][S+1000]; } };
动态规划的压缩方法:
由于这里的第二个下标,虽然sum是增加的,但是实际的矩形下标在不断的变动。因此不能用一排数组进行压缩,新旧值得更新不是按照下标遍历顺序。
采用的更新方式是:建立一个辅助数组,更新完成之后,将这个数组的值付给原数组即可
class Solution { public: int findTargetSumWays(vector<int>& nums, int S) { vector<int> dp(2001,0); dp[nums[0]+1000]=1; dp[-nums[0]+1000]+=1;//如果nums[0]为0,正负号都可以 for(int i=1;i<nums.size();i++) { vector<int> newArray(2001,0); for(int sum=-1000;sum<=1000;sum++) { if(dp[sum+1000]>0) { newArray[sum+nums[i]+1000] +=dp[sum+1000]; newArray[sum-nums[i]+1000]+=dp[sum+1000]; } } dp.assign(newArray.begin(),newArray.end()); } return S>1000?0:dp[S+1000]; } };
Evaluate Reverse Polish Notation Basic CalculatorBasic Calculator IIDifferent Ways to Add Parentheses Target Sum