What's wrong with this recursion code ??

Revision en2, by Avinash_Kaklij, 2022-08-24 21:42:54

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 ...

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en2 English Avinash_Kaklij 2022-08-24 21:42:54 58 Tiny change: 'n }\n\n' -> 'n }\n\nPlease help I'm stuck with this for a long time now ...\n'
en1 English Avinash_Kaklij 2022-08-24 21:41:34 706 Initial revision (published)