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:
Each of the array element will not exceed 100.
The array size will not exceed 200.
給定一個數組,問,有沒有一種分法,將數組分成兩個和相等的部分。
思路:
1.即在數組中查找一些數字,和爲總和的一半。
2.如果總和爲奇數,則不可能分成題目要求。
3.接下來是算法的核心。
4.以前做法:將從小到大排序,兩個數組一邊放一個的原則。總和小的那個數組得到即將要分配的數。但是這樣往往得不到最優解。需要考慮到的細節,優化點太多。
5.動態規劃中的揹包0-1問題。
代碼如下 :
function canPartition(nums){
var sum = 0;
var result = [];
if(!nums || nums.length<2){return false;}
nums.map(function(a){sum+=a});
console.log(sum);
if(sum%2){return false;}
sum /= 2;
result[0] = true;
for(var i=1; i<=nums.length; i++){
for(var j=sum; j>=nums[i-1];j--){
result[j] = (result[j] || result[j-nums[i-1]])?true:false;
}
// console.log(result.map(function(a){return a?" true":"false"}).toString());
}
return result[sum];
}