๐ŸŒ• ๐ŸŒ• 494. ็›ฎๆ ‡ๅ’Œ

ๅžไฝ›็ซฅๅญ2022ๅนด6ๆœˆ9ๆ—ฅๅฐไบŽ 1 ๅˆ†้’Ÿ

๐ŸŒ• ๐ŸŒ• 494. ็›ฎๆ ‡ๅ’Œ

้šพๅบฆ: ๐ŸŒ• ๐ŸŒ•

้—ฎ้ข˜ๆ่ฟฐ

img_18.png


่งฃๆณ•

class Solution {
    public int findTargetSumWays(int[] nums, int target) {
        // ๆ€่ทฏ๏ผš
        // pos + neg = sum
        // pos - neg = target
        // =>
        // pos = (sum + target) / 2
        // neg = (sum - target) / 2
        // ่ƒŒๅŒ…้—ฎ้ข˜
        int sum = 0;
        for(int i : nums) {
            sum += i;
        }
        // ็‰นๆฎŠๆƒ…ๅ†ต็‰นๅˆค
        if(Math.abs(target) > Math.abs(sum)) {
            return 0;
        }
        int res = sum + target;
        if((res & 1) == 1) {
            return 0;
        }
        res /= 2;
        // dp[i] : ้‡้‡ไธบ i ๆ—ถๆœ‰ๅคšๅฐ‘็งๆƒ…ๅ†ต
        int[] dp = new int[res + 1];
        dp[0] = 1;
        int len = nums.length;
        for(int j = 0; j < len; j ++) {
            for(int i = res; i - nums[j] >= 0; i --) {
                dp[i] += dp[i - nums[j]];
            }
        }
        return dp[res];
    }
}

่พ“ๅ‡บ

img_19.png

ไธŠๆฌก็ผ–่พ‘ไบŽ: 2022/6/20 ไธ‹ๅˆ8:24:47
่ดก็Œฎ่€…: liuxianzhishou