Target Sum

题目链接:https://leetcode.com/problems...

dp,可以brute force,不过这题可以memory,所以可以iteration用dp table做或者recursion:dfs+suffix array来做,还是得用二维数组保存算过的结果。这题的subproblem是到第i个数时,能够得到sum为j的ways数量,由于sum可能是负数,所以要做一个shift,使其从0开始。滚动数组优化空间。

public class Solution {
    public int findTargetSumWays(int[] nums, int S) {
        if(nums == null || nums.length == 0) return 0;
        // dp table
        int sum = 0;
        for(int num : nums) sum += num;
        if(S > sum || S < -sum) return 0;
        // dp[i][j]: the number of ways that add up to j using [0, i]
        // function: dp[i+1][j - nums[i]] = dp[i][j]
        //           dp[i+1][j + nums[i]] = dp[i][j]
        // j = [0, 2 * sum + 1]
        int[] dp = new int[2*sum + 1];
        dp[0+sum] = 1;
        for(int i = 0; i < nums.length; i++) {
            int[] next = new int[2*sum + 1];
            for(int j = 0; j < 2 * sum + 1; j++) {
                if(j - nums[i] >= 0 && dp[j] != 0) next[j-nums[i]] += dp[j];
                if(j + nums[i] < 2 * sum + 1 && dp[j] != 0) next[j+nums[i]] += dp[j];
            }
            dp = next.clone();
        }
        return dp[0 + sum + S];
    }
}

lulouch13
13 声望6 粉丝

下一篇 »
Ones and Zeroes