硬幣面值方案
阿新 • • 發佈:2019-02-03
var num=6; var n=Math.floor(Math.log(num)/Math.log(2)); var arr=[]; var tempArr=[]; var resultStr=[]; while(true) { arr[n]=1; num=num-Math.pow(2,n); if(num<=0) break; n=Math.floor(Math.log(num)/Math.log(2)); } tempArr=arr.concat(); printresult(); for(var i=1;i<arr.length;i++) { tempArr=arr.concat(); for(var j=i;j<arr.length;j++) { if(arr[j]==1||arr[j]==2) flow(j); } } //遞迴 function flow(index) { for(var j=index;j>=1;j-- ) { if(j==1) { if(tempArr[j-1]==undefined||tempArr[j-1]==0) { tempArr[j]--; tempArr[j-1]=2; printresult(); } } else { if(tempArr[j-1]==undefined||tempArr[j-1]==0) { tempArr[j]--; tempArr[j-1]=2; printresult(); flow(j-1); } else if(tempArr[j-1]==1&&tempArr[j-2]!=2&&tempArr[j-2]!=1) { tempArr[j]--; tempArr[j-1]=2; tempArr[j-2]=2; printresult(); flow(j-2); } } } } function printresult() { var str=''; for(var i=0;i<tempArr.length;i++) { if(tempArr[i]==1) { str+=(Math.pow(2,i)).toString()+" "; } if(tempArr[i]==2) { str += (Math.pow(2, i)).toString() + " "; str += (Math.pow(2, i)).toString() + " "; } } if(resultStr.indexOf(str)<0) { resultStr.push(str); console.log(str); } } console.log("種數:"+resultStr.length);