leetcode494

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:
1. The length of the given array is positive and will not exceed 20.
2. The sum of elements in the given array will not exceed 1000.
3. Your output answer is guaranteed to be fitted in a 32-bit integer.

1.DFS。O(2^n)
尝试所有+-的组合。

2.DP


本题有自带限制,就是最后的sum在1000内,其实就说明他们加减算出来的答案种类没有那么多。那如果你一直只用一个map,统计当前某一个数字有多少种方法算出来,那你遇到一个新数字的时候可以根据上一轮的map迭代出本轮的map。
dp[i][j]表示从0~i-1的数字,拼出j有多少种拼法,最后的答案是dp[last][target]

3.类DP的HashMap。
相比Map节省空间,只记着当前确切出现过的sum对象。每次根据旧map得到新map的可能性。

实现1 DFS:

class Solution {
    public int findTargetSumWays(int[] nums, int S) {
        if (nums == null) {
            return 0;
        }
        return dfs(nums, 0, S, 0);
    }
    
    private int dfs(int[] nums, int crt, int target, int offset) {
        if (offset == nums.length) {
            return crt == target ? 1 : 0;
        }
        int ans = 0;
        ans += dfs(nums, crt + nums[offset], target, offset + 1);
        ans += dfs(nums, crt - nums[offset], target, offset + 1);
        return ans;
    }
}

实现3 HashMap:

class Solution {
    public int findTargetSumWays(int[] nums, int S) {
        Map<Integer, Integer> count = new HashMap<>();
        count.put(0, 1);
        for (int num : nums) {
            Map<Integer, Integer> newCount = new HashMap<>();
            for (int sum : count.keySet()) {
                newCount.put(sum + num, newCount.getOrDefault(sum + num, 0) + count.get(sum));
                newCount.put(sum - num, newCount.getOrDefault(sum - num, 0) + count.get(sum));
            }
            count = newCount;
        }
        return count.getOrDefault(S, 0);
    }
}
原文地址:https://www.cnblogs.com/jasminemzy/p/9739247.html