- Dynamic programming
First of all, we calculate the sum
as sum of all number of nums
.
We have some conclusions as following:
- if
nums % 2 != 0
, we can immediatly return `false - otherwise, we can turn this problem into find a subset of
nums
which have total of its element equal tosum / 2
. - when we examine a element at
i
, there are two cases:nums[i]
belongs to the subsetnums[i]
doesn't belong to the subset
- if yes, recursive on the remaining elements of
nums
and find a subset have a newtotal = nums / 2 - nums[i]
- if no, recursive on the remaing elemetns of
nums
and find a subset have a newtotal = nums / 2
class Solution {
public boolean canPartition(int[] nums) {
int sum = 0;
for (int n : nums) sum += n;
if (sum % 2 != 0) return false;
return subsetSum(nums, sum / 2, 0);
}
private boolean subsetSum(int[] nums, int sum, int i) {
if (sum == 0) return true;
if (i == nums.length || sum < 0) return false;
return subsetSum(nums, sum - nums[i], i + 1) || subsetSum(nums, sum, i + 1);
}
}
❌ TLE 😢
We can improve above solution by using a dp
table to memorize the duplicate calculations.