494. Target Sum

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:

  1. The length of the given array is positive and will not exceed 20.
  2. The sum of elements in the given array will not exceed 1000.
  3. Your output answer is guaranteed to be fitted in a 32-bit integer.

题目含义:给了一个非负数的矩阵,里面的元素是[a0, a1, a2……]和一个目标值S,现在要在这些元素之间加入+或者-,使得里面的元素之间运算结果能够等于目标值S,求一共有多少种加入+或者-的方法

复制代码
 1 class Solution {
 2     
 3     
 4    int subsetSum(int[] nums, int s) {
 5 //        dp[i]表示子集合元素之和等于当前目标值的方案个数, 当前目标值等于9减去当前元素值
 6 //             当前元素等于1时,   dp[9] = dp[9] + dp[9-1]
 7 //                                dp[8] = dp[8] + dp[8-1]
 8 //                                ...
 9 //                                dp[1] = dp[1] + dp[1-1]
10 //                当前元素等于2时,dp[9] = dp[9] + dp[9-2]
11 //                                dp[8] = dp[8] + dp[8-2]
12 //                                ...
13 //                                dp[2] = dp[2] + dp[2-2]
14 //                当前元素等于3时,dp[9] = dp[9] + dp[9-3]
15 //                                dp[8] = dp[8] + dp[8-3]
16 //                                ...
17 //                                dp[3] = dp[3] + dp[3-3]
18         int[] dp = new int[s + 1];
19         dp[0] = 1;
20         for (int n : nums)
21             for (int i = s; i >= n; i--)
22                 dp[i] += dp[i - n];
23         return dp[s];
24     }
25     
26     
27     //        该方案中数组元素可以分为两组,一组是数字符号为正(P={1,3,5}),另一组数字符号为负(N={2,4})
28 //        因此: sum(1,3,5) - sum(2,4) = target
29 //        sum(1,3,5) - sum(2,4) + sum(1,3,5) + sum(2,4) = target + sum(1,3,5) + sum(2,4)
30 //        2sum(1,3,5) = target + sum(1,3,5) + sum(2,4)
31 //        2sum(P) = target + sum(nums)
32 //        sum(P) = (target + sum(nums)) / 2
33 //        由于target和sum(nums)是固定值,因此原始问题转化为求解nums中子集的和等于sum(P)的方案个数问题
34     public int findTargetSumWays(int[] nums, int S) {
35         int sum = 0;
36         for (int n : nums)
37             sum += n;
38         return sum < S || (S + sum) % 2 > 0 ? 0 : subsetSum(nums, (S + sum) / 2);        
39     }
40 }
复制代码

 

类似题目:

377. Combination Sum IV

posted @   daniel456  阅读(140)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示