|
| 1 | +/** |
| 2 | + * @param {Number} number |
| 3 | + */ |
| 4 | +export default function integerPartition(number) { |
| 5 | + // Create partition matrix for solving this task using Dynamic Programming. |
| 6 | + const partitionMatrix = Array(number + 1).fill(null).map(() => { |
| 7 | + return Array(number + 1).fill(null); |
| 8 | + }); |
| 9 | + |
| 10 | + // Fill partition matrix with initial values. |
| 11 | + |
| 12 | + // Let's fill the first row that represents how many ways we would have |
| 13 | + // to combine the numbers 1, 2, 3, ..., n with number 0. We would have zero |
| 14 | + // ways obviously since with zero number we may form only zero. |
| 15 | + for (let numberIndex = 1; numberIndex <= number; numberIndex += 1) { |
| 16 | + partitionMatrix[0][numberIndex] = 0; |
| 17 | + } |
| 18 | + |
| 19 | + // Let's fill the first row. It represents the number of way of how we can form |
| 20 | + // number zero out of numbers 0, 1, 2, ... Obviously there is only one way we could |
| 21 | + // form number 0 and it is with number 0 itself. |
| 22 | + for (let summandIndex = 0; summandIndex <= number; summandIndex += 1) { |
| 23 | + partitionMatrix[summandIndex][0] = 1; |
| 24 | + } |
| 25 | + |
| 26 | + // Now let's go through other possible options of how we could form number m out of |
| 27 | + // summands 0, 1, ..., m using Dynamic Programming approach. |
| 28 | + for (let summandIndex = 1; summandIndex <= number; summandIndex += 1) { |
| 29 | + for (let numberIndex = 1; numberIndex <= number; numberIndex += 1) { |
| 30 | + if (summandIndex > numberIndex) { |
| 31 | + // If summand number is bigger then current number itself then just it won't add |
| 32 | + // any new ways of forming the number. Thus we may just copy the number from row above. |
| 33 | + partitionMatrix[summandIndex][numberIndex] = partitionMatrix[summandIndex - 1][numberIndex]; |
| 34 | + } else { |
| 35 | + // The number of combinations would equal to number of combinations of forming the same |
| 36 | + // number but WITHOUT current summand number plus number of combinations of forming the |
| 37 | + // previous number but WITH current summand. |
| 38 | + const combosWithoutSummand = partitionMatrix[summandIndex - 1][numberIndex]; |
| 39 | + const combosWithSummand = partitionMatrix[summandIndex][numberIndex - summandIndex]; |
| 40 | + |
| 41 | + partitionMatrix[summandIndex][numberIndex] = combosWithoutSummand + combosWithSummand; |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + return partitionMatrix[number][number]; |
| 47 | +} |
0 commit comments