Subject requirements
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.
Assuming that there is a non-empty array of all positive integers, divide the numbers into two parts to ensure that the sum of the two parts is equal.
Thoughts and Codes
This is exactly the same as the 0-1 knapsack problem. The 01 knapsack problem refers to the assumption that there are n items, each of which is weight[i], and the backpack's load is k. It asks how to choose the items so that the load i n the backpack is the largest. The problem here is equivalent to having n items, each bearing an input[i], asking how to select items, so that the backpack load-bearing is good for the general weight sum of all items.
Assuming that we already know whether the first I item can constitute the weight k, we make the value dpi, then whether the first i+1 item can constitute the weight K depends on the DPI and dpi], that is, if i+1 item can constitute the weight k, there are two cases. The first one is to choose i+1 item, then we need to find out whether the first I item constitutes the weight of k-input[i+1], and the second one is not to choose the first item. Direct judgment of whether the first I items have constituted the weight of K.
The code is as follows:
public boolean canParition(int[] nums) { int sum = 0; for(int n : nums) { sum += n; } if(sum % 2 != 0) return false; int half = sum / 2; boolean[][] sums = new boolean[nums.length+1][half+1]; for(int i = 0 ; i<=nums.length ; i++) { for(int j = 0 ; j<=half ; j++) { if(i==0 && j==0){ sums[i][j] = true; }else if(i==0) { sums[i][j] = false; }else if(j==0){ sums[i][j] = true; }else { sums[i][j] = sums[i-1][j] || (nums[i-1] <= j ? sums[i-1][j-nums[i-1]] : false); } } } return sums[nums.length][half]; }