Java implementation LeetCode 494 goals and

494. objectives and

Given an array of non-negative integer, a1, a2, ..., an, and a number of goals, S. Now you have two symbols + and -. For any integer array, you can from + or - to select a symbol added earlier.

And the final array can return all the way to add the number of symbols is the target number of S.

Example 1:

Input: nums: [1, 1, 1, 1, 1], S: 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 make the ultimate goal and three.
note:

An array of non-empty, and a length of no more than 20.
The initial array and not more than 1,000.
The end result can be returned able to save the 32-bit integer.

  494
   输入: nums: [1, 1, 1, 1, 1], S: 3
  输出: 5
  解释:
   -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
  
  sum(P) 前面符号为+的集合;sum(N) 前面符号为减号的集合
  所以题目可以转化为
 sum(P) - sum(N) = target 
 => sum(nums) + sum(P) - sum(N) = target + sum(nums)
 => 2 * sum(P) = target + sum(nums) 
=> sum(P) = (target + sum(nums)) / 2
因此题目转化为01背包,也就是能组合成容量为sum(P)的方式有多少种
class Solution {

       public static int findTargetSumWays(int[] nums, int S) {
        int sum = 0;
        for (int num : nums) {
            sum += num;
        }
        if (sum < S || (sum + S) % 2 == 1) {
            return 0;
        }
        int w = (sum + S) / 2;
        int[] dp = new int[w + 1];
        dp[0] = 1;
        for (int num : nums) {
            for (int j = w; j >= num; j--) {
                dp[j] += dp[j - num];
            }
        }
        return dp[w];
    }
}
Released 1592 original articles · won praise 20000 + · Views 2.5 million +

Guess you like

Origin blog.csdn.net/a1439775520/article/details/105017182