# 494. 目标和 (opens new window)

01 背包

class Solution {
    public int findTargetSumWays(int[] nums, int target) {
        int sum = 0;
        for (int x: nums) sum+=x;
        if ((sum-target) %2  > 0 || sum < target) return 0;
        int V = (sum - target) >> 1;

        int[]dp = new int[V+1];
        dp[0] = 1;
        for (int i = 0; i< nums.length; i++){
            for (int v = V; v>= nums[i]; v--){
                dp[v] += dp[v- nums[i]] ;
            }
        }
        return dp[V];
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# 1049. 最后一块石头的重量 II (opens new window)

class Solution {
    public int lastStoneWeightII(int[] stones) {
        int n = stones.length;
        int sum = 0;
        for (int x : stones) sum += x;
        int V = sum / 2;
        int[] f = new int[V + 1];
        Arrays.fill(f, 0);

        for (int i = 0; i < n; i++) {
            for (int j = V; j >= stones[i]; j--) {
                f[j] = Math.max(f[j], f[j-stones[i]] + stones[i]);
            }
        }
        return sum - 2* f[V];
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17