494. Objective and 01 backpack problem (dynamic programming) and use of recursion

First of all, I saw the title of this question. I feel that it is very similar to the previous combination problem. I can directly find part of the solution to the problem. First, I dynamically search for the array, omit the array that has been read, and then constantly update the value of S, so that the final When the length of S to the array is 1, it is equal to the value of the array. This method is the method I first thought of, that is, to recurse our function, it is enough to continuously update the array and the final S value. Introduced, the code is as follows:

    public int findTargetSumWays(int[] nums, int S) {
        int res = 0;
        if (nums.length >= 2) {
            return findTargetSumWays(Arrays.copyOfRange(nums, 0, nums.length - 1), S+nums[nums.length-1])
                    +findTargetSumWays(Arrays.copyOfRange(nums, 0, nums.length - 1), S-nums[nums.length-1]);
        } else {
            if (nums.length == 1 && nums[0] == S) {
                res++;
            }
            if (nums.length == 1 && nums[0] == -S) {
                res++;
            }
                    return res;
        }

    }

The second method is not much different from the dynamic programming I did yesterday, which is the complicated 01 backpack problem: we set a two-dimensional array int [] [] dp = new int [i] [j]; i refers to the position of the elements we traverse the array, j refers to the sum we get when traversing to the array i. We traverse all the arrays for each i, update all the arrays, and finally find the sum of S, the code is as follows:

    public int findTargetSumWays(int[] nums, int S) {
        int[][] dp = new int[nums.length][2001];
        dp[0][nums[0] + 1000] = 1;
        dp[0][-nums[0] + 1000] += 1;
        for (int i = 1; i < nums.length; i++) {
            for (int sum = -1000; sum <= 1000; sum++) {
                if (dp[i - 1][sum + 1000] > 0) {
                    dp[i][sum + nums[i] + 1000] += dp[i - 1][sum + 1000];
                    dp[i][sum - nums[i] + 1000] += dp[i - 1][sum + 1000];
                }
            }
        }
        return S > 1000 ? 0 : dp[nums.length - 1][S + 1000];
    }
}

 

Published 17 original articles · Likes0 · Visits 152

Guess you like

Origin blog.csdn.net/qq_33286699/article/details/105034859