python整数拆分dp算法_整数拆分-dp问题

/**

* @param {number} number

* @return {number}*/exportdefaultfunction integerPartition(number) {//Create partition matrix for solving this task using Dynamic Programming.

const partitionMatrix = Array(number + 1).fill(null).map(() =>{return Array(number + 1).fill(null);

});for (let numberIndex = 1; numberIndex <= number; numberIndex += 1) {

partitionMatrix[0][numberIndex] = 0;

}for (let summandIndex = 0; summandIndex <= number; summandIndex += 1) {

partitionMatrix[summandIndex][0] = 1;

}//Now let's go through other possible options of how we could form number m out of//summands 0, 1, ..., m using Dynamic Programming approach.

for (let summandIndex = 1; summandIndex <= number; summandIndex += 1) {//行-被加数for (let numberIndex = 1; numberIndex <= number; numberIndex += 1) {//input代表的列if (summandIndex >numberIndex) {//If summand number is bigger then current number itself then just it won't add//any new ways of forming the number. Thus we may just copy the number from row above.

partitionMatrix[summandIndex][numberIndex] = partitionMatrix[summandIndex - 1][numberIndex];

}else{/** The number of combinations would equal to number of combinations of forming the same

* number but WITHOUT current summand number PLUS number of combinations of forming the

* number but WITH current summand.

*

* Example:

* Number of ways to form 5 using summands {0, 1, 2} would equal the SUM of:

* - number of ways to form 5 using summands {0, 1} (we've excluded summand 2)

* - number of ways to form 3 (because 5 - 2 = 3) using summands {0, 1, 2}

* (we've included summand 2)*/

const combosWithoutSummand = partitionMatrix[summandIndex - 1][numberIndex];const combosWithSummand = partitionMatrix[summandIndex][numberIndex -summandIndex];

partitionMatrix[summandIndex][numberIndex]= combosWithoutSummand +combosWithSummand;

}

}

}returnpartitionMatrix[number][number];

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值