您的位置:首页 > 其它

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。

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));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: