494. Target Sum

网友投稿 628 2022-09-04

494. Target Sum

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: 5Explanation: -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

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.

class Solution private int cnt = 0; public int findTargetSumWays(int[] nums, int S) { if (nums == null) return 0; dfs(nums, S, 0, 0); return cnt; } public void dfs(int[] nums, int s, int k, int sum) { if (k == nums.length) { if (s == sum) cnt ++; return ; } dfs(nums, s, k+1, sum+nums[k]); dfs(nums, s, k+1, sum-nums[k]); }}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:最易懂的数据库异地多活方案(异地多活数据同步)
下一篇:分布式架构的演进:图文并茂(分布式架构原理和实现)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~