-
-
Save demobo-com/df4caf9f6f35237af6229bc4e22d9a4f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const _ = require('lodash'); | |
const getCombination = arr => i => arr.filter((v,j) => i & Math.pow(2, j)); | |
const solve = (unders, ups) => { | |
if (!unders.length || !ups.length) return 0; | |
const m = Math.pow(2, unders.length); | |
const n = Math.pow(2, ups.length); | |
const getUndersCombination = getCombination(unders); | |
const getUpsCombination = getCombination(ups); | |
const underSumMap = {}; | |
for (var i = 0; i < m; i++) { | |
const targetSum = _.sum(getUndersCombination(i)); | |
if (!underSumMap[targetSum]) underSumMap[targetSum] = i; | |
} | |
let undersIndex, upsIndex; | |
for (var j = 1; j < n - 1; j++) { | |
const targetSum = _.sum(getUpsCombination(j)); | |
undersIndex = underSumMap[targetSum]; | |
upsIndex = j; | |
if (undersIndex) break; | |
} | |
if (!undersIndex) return unders.length + ups.length - 1; | |
return solve(getUndersCombination(undersIndex), getUpsCombination(upsIndex)) | |
+ | |
solve(getUndersCombination(m - 1 - undersIndex), getUpsCombination(n - 1 - upsIndex)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment