Leetcode 416. Split Equal Sum Subsets (01 Knapsack)
topic
You are given a non-empty array nums containing only positive integers. Please judge whether this array can be divided into two subsets so that the sum of the elements of the two subsets is equal.
1 <= nums.length <= 200
1 <= nums[i] <= 100
solution
Dynamic programming (01 backpack): first consider the special case: since all elements are positive integers, a single element or all elements cannot be divided if the sum is an odd number.
Then there is the general situation: the topic can be transformed into selecting some elements and making the sum half of the sum of all elements, so you can think of 01 backpack
Define the state (sub-problem): dp[i][j] is the subscript (including) the first i elements, and whether j can appear, initialization: j is 0, it is true, otherwise it is false, and finally judge dp[n- 1][m/2]
Transfer equation: if adding the current element dp[i-1][j-num[i]] or not adding dp[i-1][j] is true, then dp[i][j] is true (dp[i][j] can be used i-1][j-num[i]] | dp[i-1][j])
Space compression: Since i is only related to i-1, you can use the scrolling array dp[2][m/2], and if you traverse j in reverse order, you can only use the previous elements when traversing, and the assignment will not affect the previous elements, so use the rolling array dp[m/2]
The number of elements is n, the sum of all elements is m, time complexity: O(n*m), space complexity: O(m)