devops 信创在数字经济时代提升企业竞争力的关键策略
628
2022-09-04
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小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~