# 查找数组中具有给定总和的子数组的数量

##### 问题描述投票：0回答：3

``````function getSubArrayCount(arr, sum) {

for (var i = 0; i < arr.length; i++) {
var str = [];
var csum= 0;
var output = 0;

for (var j = i; j < arr.length; j++) {
csum+= arr[j];
str.push(arr[j]);
if (csum== sum) {
return(str[i]);
}
}
}
}

console.log(getSubArrayCount([1,2,3,2,1,8,-3],5))
``````
javascript algorithm
##### 3个回答
2

``````function getSubArrayCount(arr, sum) {
let map = new Map();
var cumsum = 0; var cnt = 0;
map.set(0, 1);
for (var i = 0; i < arr.length; i++) {
cumsum += arr[i];
if (map.has(cumsum - sum))
cnt += map.get(cumsum - sum);
if (map.has(cumsum))
map.set(cumsum, map.get(cumsum) + 1);
else
map.set(cumsum, 1);
}
return cnt;
}

console.log(getSubArrayCount([1,2,3,2,1,8,-3],5));   //3
console.log(getSubArrayCount([1,-2,3,-3,4,-2,-1,-1],0));   //5``````

1

``````function getSubArrayCount(arr, sum) {
var output = 0, csum = 0;
for (var i = 0; i < arr.length; i++) {
for (var j = i; j < arr.length; j++) {
csum+= arr[j];
if (csum== sum) {
output++;
}
}
csum= 0;
}

return output;
}

console.log(getSubArrayCount([1,2,3,2,1,8,-3],5));``````

0

``````let sub= (a,n)=> a.filter((x,i)=> n&(1<<i))
``````

`````` [ 1, 2, 3, 2, 1, 8,-3 ]
1  0  1  0  0  1  1      ->     [1,3,8,-3]
``````

``````function getSubArrayCount(a,sum) {
let r=0, sub= (a,n)=> a.filter((x,i)=> n&(1<<i));
for(let i=0; i<2**a.length; i++)
sub(a,i).reduce((s,c)=>s+c,0)==sum ? r++ : 0;
return r;
}

console.log('[1,2,3,2,1,8,-3] sum=5 => ', getSubArrayCount([1,2,3,2,1,8,-3],5) );
console.log('[1,2,3,4] sum=10       => ', getSubArrayCount([1,2,3,4],10) );
console.log('[1,2,3,-3] sum=3       => ', getSubArrayCount([1,2,3,-3],3) );``````