Description
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.
Note:
- The length of the given array is positive and will not exceed 20.
- The sum of elements in the given array will not exceed 1000.
- Your output answer is guaranteed to be fitted in a 32-bit integer.
分析
题目的意思是:给定一个数组和一个target,可以指定每个数的正负号,然后求和等于target,求有多少种指定方式。
- 用sum§表示被标记为正数的子集合,N表示被标记为负数的子集合,然后根据题意要满足下面的条件:
sum(P) - sum(N) = target
sum(P) + sum(N) + sum(P) - sum(N) = target + sum(P) + sum(N)
2 * sum(P) = target + sum(nums)
nums = {1,2,3,4,5}, target=3
- 求解nums中子集合只和为sum§的方案个数(nums中所有元素都是非负)
给定集合nums={1,2,3,4,5}, 求解子集,使子集中元素之和等于9 = new_target = sum§ = (target+sum(nums))/2
当前元素等于1时,dp[9] = dp[9] + dp[9-1]
dp[8] = dp[8] + dp[8-1]
…
dp[1] = dp[1] + dp[1-1]
当前元素等于2时,dp[9] = dp[9] + dp[9-2]
dp[8] = dp[8] + dp[8-2]
…
dp[2] = dp[2] + dp[2-2]
当前元素等于3时,dp[9] = dp[9] + dp[9-3]
dp[8] = dp[8] + dp[8-3]
…
dp[3] = dp[3] + dp[3-3]
当前元素等于4时,
…
当前元素等于5时,
…
dp[5] = dp[5] + dp[5-5]
最后返回dp[9]即是所求的解
代码
class Solution {
public:
int findTargetSumWays(vector<int>& nums, int S) {
int sum=accumulate(nums.begin(),nums.end(),0);
return sum<S||(S+sum) & 1 ? 0:subsetSum(nums,(sum+S)>>1);
}
int subsetSum(vector<int>& nums,int s ){
int dp[s+1]={0};
dp[0]=1;
for(int n:nums){
for(int i=s;i>=n;i--){
dp[i]+=dp[i-n];
}
}
return dp[s];
}
};
Python代码
class Solution:
def findTargetSumWays(self, nums: List[int], target: int) -> int:
total = sum(nums)
# A: 所有采用+的数的集合,B:所有采用-的数的集合
# sum(A) - sum(B) = S
# sum(A) + sum(A) = S + sum(B) + sum(A)
# sum(A) = (S + sum)/2
if total<abs(target) or (total+target)%2==1:
return 0
n = (total+target) //2
m = len(nums)
dp =[[0 for _ in range(n+1)] for _ in range(m+1)]
# 背包问题
# dp[i][j]: 在前i个数中选择恰好装满背包j有几种方法
# dp[m][target]是结果
# dp[i][j] = dp[i-1][j] + dp[i-1][j-nums[i]] 第i个物品不装的方案个数:dp[i-1][j],第i个物品装的方案个数:dp[i-1][j-nums[i-1]]
for i in range(m+1):
dp[i][0]=1
for i in range(1, m+1):
for j in range(n+1):
dp[i][j]=dp[i-1][j]
if j>=nums[i-1]:
dp[i][j]+=dp[i-1][j-nums[i-1]]
return dp[-1][-1]
参考文献
494. Target Sum
leetcode – 494. Target Sum【数学转化 + 动态规划】
494. Target Sum
[leetcode]494. 目标和