494. Target Sum
来源:互联网 发布:汽车单片机控制灯光 编辑:程序博客网 时间:2024/06/03 15:44
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 = 3There 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.
public class Solution { int solution = 0; public int findTargetSumWays(int[] nums, int S) { if(nums == null || nums.length == 0){ return 0; } dfs(nums, 0, S, 0); return solution; } public void dfs(int[] nums, int start, int S, int sum){ if(start == nums.length){ //这里要等于,因为要求完最后一个数字 if(sum == S){ solution++; } return; } dfs(nums, start+1, S, sum+nums[start]); dfs(nums, start+1, S, sum-nums[start]); }}
public class Solution { public int findTargetSumWays(int[] nums, int S) { int sum = 0; for (int a : nums) { sum += a; } if (sum < Math.abs(S)) { return 0; } //init for dp int doubleSum = sum << 1; int[][] dp = new int[nums.length][doubleSum + 1]; if (nums[0] == 0) { dp[0][sum] = 2; } else { dp[0][sum - nums[0]] = 1; dp[0][sum + nums[0]] = 1; } //dp for (int i = 1; i < nums.length; i++) { for (int j = 0; j <= doubleSum; j++) { if (j - nums[i] >= 0) { dp[i][j] += dp[i - 1][j - nums[i]]; } if (j + nums[i] <= doubleSum) { dp[i][j] += dp[i - 1][j + nums[i]]; } } } return dp[nums.length - 1][S + sum]; }}
阅读全文
0 0
- LeetCode 494. Target Sum
- [LeetCode]494. Target Sum
- 494. Target Sum
- [leetcode]494. Target Sum
- 494. Target Sum
- Leetcode 494. Target Sum
- 494. Target Sum -Medium
- 494. Target Sum
- Leetcode-494. Target Sum
- 494. Target Sum
- Leetcode 494. Target Sum
- 494. Target Sum
- leetcode-494. Target Sum
- 494. Target Sum
- 494. Target Sum
- 494. Target Sum
- 494. Target Sum
- 494. Target Sum
- [Unity&多人游戏插件]GameSparks 的下载 安装以及简单的说明
- Android获取手机的IMEI
- linux应用调试之自制系统调用、编写进程查看器(一)
- Java--反射机制示例
- java-常见开源库2
- 494. Target Sum
- Thread学习之资源共享
- swing 飞机大战 二 实现地图的滚动
- 398. Random Pick Index
- Javascript中事件机制详解
- 0611 js写水仙花数
- 【算法】我拿走了哪个数?
- 二叉搜索树的插入
- aliyun 配置https