Created
January 2, 2017 11:29
-
-
Save cyyeh/a7ee16ed51078f4d7057671996880a2c 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
function count(arr, arrLength, target) { | |
if (target === 0) | |
return 1; | |
if (target < 0 || (arrLength <= 0 && target >= 1)) | |
return 0; | |
return count(arr, arrLength - 1, target) + count(arr, arrLength, target-arr[arrLength - 1]); | |
} | |
function count_dp(arr, arrLength, target) { | |
var table = new Array(arrLength + 1); | |
for (var i = 0; i <= table.length; i++) { | |
table[i] = 0; | |
} | |
table[0] = 1; | |
for (var k = 0; k < arrLength; k++) { | |
for (var j = arr[k]; j <= target; j++) { | |
table[j] += table[j - arr[k]]; | |
} | |
} | |
return table[target]; | |
} | |
var arr = [1, 2, 3]; | |
console.log(count_dp(arr, arr.length, 4)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment