思路:
1. 如果当前剩余总和小于最大值:
a.循环当前剩余数字
b.递归执行
c. 用一个变量bestS存小于最大值情况下的最大总和
var bestS = {val:0,str:""};
var LIMIT ;
Array.prototype.sum = function(){
var s = 0;
for(var i = 0;i < this.length;i++){
s+= this[i];
}
return s;
}
function f(bagArr,copyArr,start){
var arrS = copyArr.sum();
if(arrS < LIMIT && arrS > bestS.val){
bestS = arrS > bestS.val ? {val:arrS,str:copyArr.join(',')} : bestS;
}
for(var i = start;i<bagArr.length;i++){
copyArr.push(bagArr[i]);
f(bagArr,copyArr,i+1);
copyArr.splice(copyArr.length-1,1);
}
}
LIMIT = 197;
f(new Array(49,28,119,50,78,48,29,49,52,48,29,49,52,48,29,49,52),new Array(),0);
console.log(bestS);