解题思路:
- 用双循环去更新dp[j]:dp[j] = dp[j] || dp[j - nums[i]]
代码:
class Solution {
public boolean canPartition(int[] nums) {
int len = nums.length;
int sum = 0;
for(int i = 0; i < len; i++){
sum += nums[i];
}
if(sum % 2 != 0) return false;
int target = sum/2;
boolean[] dp = new boolean[target + 1];
dp[0] = true;
for(int i = 1; i <= len; i++){
for(int j = target; j >= nums[i - 1]; j--){
dp[j] = dp[j] || dp[j - nums[i - 1]];
}
}
return dp[target];
}
}
网友评论