扫码关注官方订阅号
js数组:a[n]定量ma[0],a[1]......a[n]已知,m已知;怎样计算出哪几个数相加的和为定量m?最终输出这几个数的index
学习是最好的投资!
搜索背包问题
我能想到就是循环遍历,一遍一遍来吧。。
关键词: 01背包问题
背包问题,但要数组2边同时开始遍历,时间复杂度就为n,效率高一倍。
不知道效率怎么样实现了再说吧~~
function getcombinationAndMatched(initval,array,targetValue,someGroup){ var result=[]; var matched=[]; var startIndex; if(someGroup.index.length===0){ startIndex=-1; }else{ startIndex=someGroup.index[someGroup.index.length-1]; } for(var i=startIndex+1;i<array.length;i++){ if(initval+array[i]<=targetValue) { if(initval+array[i]===targetValue){ matched.push(someGroup.index.slice(0).concat([i])); someGroup.value=targetValue; someGroup.index.push(i); }else{ result.push({ value:initval+array[i], index:someGroup.index.slice(0).concat([i]) }); } }else{ break; } } return { matched:matched, result:result } } function getMatchedGroup(groupArray,orgArray,targetValue){ var matched=[]; for(var q=0;q<groupArray.length;q++){ var groupResult=getcombinationAndMatched(groupArray[q].value,orgArray,targetValue,groupArray[q]); matched=matched.concat(groupResult.matched); if(groupResult.result.length!=0){ var _matched_=getMatchedGroup(groupResult.result,orgArray,targetValue); matched=matched.concat(_matched_); } } return matched; } var orgArray=[1,2,3,4,5,6,7,8,9,20,30]; var targetValue=41; orgArray.sort(function(a, b) { return a - b; }); var subArray=[]; var findIndex=orgArray.findIndex(function(item){ return item>targetValue; }); if(findIndex===-1){ subArray=orgArray; }else{ subArray=orgArray.slice(0,findIndex); } var result=getMatchedGroup([{ value:0, index:[] }],subArray,targetValue); //console.log(result); result.forEach(function(item){ console.log(item.map(function(valueIndex){ return orgArray[valueIndex]; }).join(',')); });
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
搜索背包问题
我能想到就是循环遍历,一遍一遍来吧。。
关键词: 01背包问题
背包问题,但要数组2边同时开始遍历,时间复杂度就为n,效率高一倍。
不知道效率怎么样
实现了再说吧~~