LeetCode-Add to List 494. Target Sum

来源:互联网 发布:电池优化 编辑:程序博客网 时间:2024/06/02 14:49

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));    }}
原创粉丝点击