zoukankan      html  css  js  c++  java
  • [LC] 494. Target Sum

    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];
        }
    }



  • 相关阅读:
    Perfect ScrollBar插件使用方法
    分享WEBAPP利用纯HTML5实现拨打电话,打开相册,打开摄像头源码
    一周心得
    19赵亮龙07杨康
    李娜跟姜山
    一周心得
    对结对编程的个人理解
    周心得和总结
    关于IT行业抄袭和借鉴
    第三周总结
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12216088.html
Copyright © 2011-2022 走看看