LeetCode-Add to List 494. Target Sum
2017-09-13 15:46
417 查看
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.
说了这么多废话,就是求N个数(有相对顺序)相加相减如何等于target。
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.
说了这么多废话,就是求N个数(有相对顺序)相加相减如何等于target。
package solutions._494; class Solution { private int count; private int target; private void DFS(int[] nums, int i, int s) { if (i == nums.length) { if (s == target) { count++; } return; } DFS(nums, i + 1, s + nums[i]); DFS(nums, i + 1, s - nums[i]); } public int findTargetSumWays(int[] nums, int S) { count = 0; target = S; DFS(nums, 0, 0); return count; } public static void main(String[] args) { Solution solution = new Solution(); int[] arr = {1, 1, 1, 1, 1}; int target = 3; System.out.println(solution.findTargetSumWays(arr, target)); } }
相关文章推荐
- [leetcode] 64. Minimum Path Sum Add to List
- leetcode- Add to List 458. Poor Pigs
- 【LeetCode】417. Pacific Atlantic Water Flow Add to List
- 【LeetCode24】. Swap Nodes in Pairs Add to List
- leetcode 500 Keyboard Row Add to List
- LeetCode 25 Reverse Nodes in k-Group Add to List (划分list为k组)
- leetCode_Add to List 206. Reverse Linked List
- Leetcode--Add to List 201. Bitwise AND of Numbers Range
- Leetcode--Add to List 215. Kth Largest Element in an Array
- leetcode_ Add to List 121. Best Time to Buy and Sell Stock
- LeetCode 143 Reorder List Add to List
- Leetcode--Add to List 374. Guess Number Higher or Lower
- LeetCode406. Queue Reconstruction by Height Add to List
- leetcode_ Add to List 108. Convert Sorted Array to Binary Search Tree
- 【leedcode】 Add to List 303. Range Sum Query - Immutable
- LeetCode- Add to List 88. Merge Sorted Array
- [Leetcode] 2.Add Two Numbers(List To Long,模拟)
- [leetcode]500.Keyboard Row Add to List
- leetcode- Add to List 669. Trim a Binary Search Tree
- LeetCode- Add to List 84. Largest Rectangle in Histogram