算法训练Day41|416. 分割等和子集

背包问题:

LeetCode:416. 分割等和子集 

416. 分割等和子集 - 力扣(LeetCode)

1.思路

①确定dp[]数组的含义,dp[i]:表示重量为 i 的背包所能装下的最大价值.
②确定递推公式,倒叙加入.
③初始化,默认为0即可.
④确认遍历顺序,先遍历物品,再遍历背包,背包从大到小遍历.
⑤举例代入,打印dp[]数组.

2.代码实现

 1class Solution {
 2    public boolean canPartition(int[] nums) {
 3        int sum = 0;
 4        for (int num : nums) {
 5            sum += num;
 6        }
 7        if (sum % 2 != 0) {
 8            return false;
 9        }
10        int target = sum / 2;
11        // target 代表重量和价值 则dp[] 数组要达到target,需要创建数组范围为:[0, target]
12        int[] dp = new int[target + 1];
13        for (int i = 0; i < nums.length; i++) { // 先遍历物品
14            for (int j = target; j >= nums[i]; j--) {
15                // 再遍历背包
16                dp[j] = Math.max(dp[j], dp[j - nums[i]] + nums[i]);
17            }
18        }
19        return dp[target] == target;
20    }
21}

3.复杂度分析

时间复杂度:O(n^2).
空间复杂度:O(n).

你可能感兴趣的:(算法,leetcode,数据结构,java)