Avinash_Kaklij's blog

By Avinash_Kaklij, history, 20 months ago, In English

Question is : Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k. A subarray is a contiguous non-empty sequence of elements within an array.

My code :

int res=0;
void solve(vector<int>& nums, int k, int n, int curr) {
    if(n==0)    return;
    curr+=nums[n-1];
    if(curr==k) {
        res++;
        return;
    } else {
        solve(nums, k, n-1, curr);
    }
    solve(nums, k, n-1, 0);
}

int subarraySum(vector<int>& nums, int k) {
    int n=nums.size();
    solve(nums, k, n, 0);
    return res;
}

Please help I'm stuck with this for a long time now ...

Full text and comments »

  • Vote: I like it
  • 0
  • Vote: I do not like it