2017.9.6.
题目真的是越来越难了呢,很多思路我完全没有。别人的思路和代码也是勉勉强强可以看懂,但是自己是完全写不出来那么巧妙的思路的。
这个题目加收藏了,一定还是要好好琢磨的。
public class Solution {
/**
* @param nums a non-empty array only positive integers
* @return return true if can partition or false
*/
public boolean canPartition(int[] nums) {
// Write your code here
int length = nums.length;
if(length <= 1){
return false;
}
int sum = 0;
for(int num : nums){
sum += num;
}
if(sum%2 == 1){
return false;
}
sum /= 2;
boolean []dp = new boolean[sum + 1];
//dp【i】用来表示,数组中是否存在 和为 i 的子集合。
//状态转移,感觉真是巧妙啊。
dp[0] = true;
for(int i = 0; i < length; i++){
for(int j = sum; j>= nums[i]; j--){
dp[j] = dp[j] || dp[j - nums[i]];
}
}
return dp[sum];
}
}