码迷,mamicode.com
首页 > 其他好文 > 详细

[LC] 494. Target Sum

时间:2020-01-20 09:38:14      阅读:92      评论:0      收藏:0      [点我收藏+]

标签:and   find   for   target   sig   col   xpl   amp   +=   

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 num

class Solution {
    public int findTargetSumWays(int[] nums, int S) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int sum = 0;
        for (int num: nums) {
            sum += num;
        }
        // unreachable sum
        if (S > sum || S < -sum) {
            return 0;
        }
        int[] arr = new int[2 * sum + 1];
        arr[sum] = 1;
        for (int i = 0; i < nums.length; i++) {
            int[] curArr = new int[2 * sum + 1];
            for (int j = 0; j < arr.length; j++) {
                if (arr[j] != 0) {
                    // dp from center to both sides
                    curArr[j - nums[i]] += arr[j];
                    curArr[j + nums[i]] += arr[j];
                }
            }
            arr = curArr;
        }
        return arr[sum + S];
    }
}

 




[LC] 494. Target Sum

标签:and   find   for   target   sig   col   xpl   amp   +=   

原文地址:https://www.cnblogs.com/xuanlu/p/12216088.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!