跳到主要内容

Partition Equal Subset Sum

描述

Given a non-empty array nums containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.

Example 1:

Input: nums = [1,5,11,5] > Output: true Explanation: The array can be partitioned as [1, 5, 5] and [11].

Example 2:

Input: nums = [1,2,3,5] > Output: false Explanation: The array cannot be partitioned into equal sum subsets.

Constraints:

  • 1nums.length2001 \leq nums.length \leq 200
  • 1nums[i]1001 \leq nums[i] \leq 100

分析

本题是一个0-1背包,且背包恰好装满的问题。令每个物品ii的重量wiw_inums[i],价值viv_i为 0,背包能容纳的最大重量W=12iwiW=\frac{1}{2}\sum_i w_i,该问题就变成,选择若干物品,能否恰好填满背包?

f(i, j)表示前 ii 个物品能否填满容量为 jj 的背包,则状态转移方程为:

f(i,j)=f(i1,j)f(i1,jwi)f(i,j) = f(i-1,j) \lor f(i-1, j-w_i)

代码

# TODO

相关题目