You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求将迭代实现的int arraySum函数转换为递归实现方法

Converting Iterative Array Sum to Recursive Implementation

First, let's address a couple of issues in your original iterative code to ensure correctness:

  • You're overwriting the input parameter n with a.size()—if n was intended to specify how many elements to sum (rather than always using the full array), this could lead to unexpected behavior.
  • The loop starts at i=1, which skips the first element a[0] entirely!

Here's the corrected iterative version for reference:

int arraySum(int[] a, int n) {
    int sum = 0;
    // Use the input n instead of overwriting it; if you intend to sum the full array, set n = a.size() explicitly
    for (int i = 0; i < n; i++) {
        sum += a[i];
    }
    return sum;
}

Recursive Approach: Core Idea

Recursion works by breaking a problem into smaller subproblems until we hit a base case (a trivial problem we can solve directly). For array summation:

  • Base Case: If there are no elements left to sum (n <= 0), return 0.
  • Recursive Step: The sum of the first n elements equals the first element plus the sum of the remaining n-1 elements.

Recursive Implementation

int arraySum(int[] a, int n) {
    // Base case: no elements to sum, return 0
    if (n <= 0) {
        return 0;
    }
    // Recursive step: add first element to the sum of the rest of the array
    return a[0] + arraySum(a + 1, n - 1);
}

How It Works (Example Walkthrough)

Let's say we call arraySum([1, 2, 3], 3):

  1. arraySum([1,2,3],3) → returns 1 + arraySum([2,3],2)
  2. arraySum([2,3],2) → returns 2 + arraySum([3],1)
  3. arraySum([3],1) → returns 3 + arraySum([],0)
  4. arraySum([],0) → hits the base case, returns 0
  5. Unwinding the recursion: 3+0=3 → 2+3=5 → 1+5=6 (the correct total sum)

Alternative for std::vector

If you're working with std::vector instead of raw arrays, you can adjust the function to use an index instead of pointer arithmetic for cleaner readability:

int arraySum(const std::vector<int>& a, int index = 0) {
    if (index >= a.size()) {
        return 0;
    }
    return a[index] + arraySum(a, index + 1);
}

Quick Note on Edge Cases

  • For empty arrays or n=0, the function correctly returns 0.
  • Be mindful of very large arrays: recursion uses the call stack, so extremely large n could trigger a stack overflow. For most practical use cases, though, this isn't a problem.

内容的提问来源于stack exchange,提问作者ṁḥā Ābōū Āl-Tīmēn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:58:24