Weekly LeetCode Algorithm Questions (18) 494. Target Sum

Weekly LeetCode Algorithm Questions (18)

Subject: 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.

solution analysis

At the beginning of this question, my idea is recursive, that is, starting from the first element, it can be divided into two nodes by the positive and negative signs, and when it reaches the second element, it will continue to be divided into two nodes, so that there are n elements There are final n^2 paths, but this trial found that it timed out when n=20.

But because many such paths end up in the same way, the same sum is obtained, and the interval between the sum of the positive and negative arrays (because the maximum can reach the positive sum, the minimum can reach the negative sum, will not be outside this interval) is shorter. If within this interval, each path is recorded one step at a time, then the number of paths that can reach the target point after n steps will be displayed.

C++ code

class Solution {
public:
    int findTargetSumWays(vector<int>& nums, int S) {
        int len = nums.size();
        if (len == 0) {
            return 0;
        }
        int sum = 0;
        for (int i = len - 1; i >= 0; i--) {
            sum += nums[i];
        }
        if (S > sum || S < -sum) {
            return 0;
        }
        vector< vector<int> > dp;
        dp.resize(len, vector<int>(2 * sum + 1, 0));
        dp[0][sum + nums[0]]++;
        dp[0][sum - nums[0]]++;
        for (int i = 1; i < len; i++) {
            for (int j = 0; j < 2 * sum + 1; j++) {
                if (j + nums[i] < 2 * sum + 1) {
                    dp[i][j + nums[i]] += dp[i - 1][j]; 
                }
                if (j - nums[i] >= 0) {
                    dp[i][j - nums[i]] += dp[i - 1][j];
                }
            }
        }
        return dp[len - 1][sum + S];
    }
};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325643344&siteId=291194637