416. Partition Equal Subset Sum

Given a non-empty array 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.

Note:

  1. Each of the array element will not exceed 100.

  2. The array size will not exceed 200.

Example 1:

Input: [1, 5, 11, 5]

Output: true

Explanation: The array can be partitioned as [1, 5, 5] and [11].

Example 2:

Input: [1, 2, 3, 5]

Output: false

Explanation: The array cannot be partitioned into equal sum subsets.
circle-info

既然要找到兩個子集合的和相等,所以所有數字的總合不能是奇數。

dp[i][j]代表nums array裡index = 0到index = i - 1的數字中能否組成和為j的子集合。

DP state transition: dp[i][j] = dp[i - 1][j] || dp[i - 1][j - nums[i - 1]] if j >= nums[i - 1] dp[i][j] = dp[i - 1][j] if j < nums[i - 1]

circle-info

仔細觀察可以發現dp[i][j]只需要前一個的row的結果,不需要用到2-D dp array去記錄所有過程,只需要前一排的結果。所以可以只用一個1-D dp array去計算。注意loop target的時候要從大到小,因為這樣才不會重複計算。把2D dp關係式用二維圖形畫出來就顯而易見。

circle-info

Recursion DFS在這比bottom-up DP有效率。

Last updated