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

求计算组合数NCK的递归代码的时间与空间复杂度

Recursive Binomial Coefficient: Time & Space Complexity Breakdown

First, let's recap what this code does: it calculates the binomial coefficient ( C(n,k) ) (the number of ways to choose k elements from a set of n) using the standard recursive formula:

( C(n,k) = C(n-1,k-1) + C(n-1,k) )

It includes handy optimizations for edge cases to avoid unnecessary recursion:

  • Returns 1 immediately if ( k=0 ) or ( k=n ) (there's only one way to choose nothing or everything)
  • Returns n immediately if ( k=1 ) (choosing one element from n has exactly n options)

Time Complexity

This implementation suffers from massive redundant subproblem calculations, which makes its time complexity exponential:

  • Worst Case: When ( k \approx n/2 ), the binomial coefficient is at its largest, and the recursive tree expands fully. Here, time complexity hits ( O(2^n) ). You'll see globalhitsToThisMethod skyrocket here because nearly every subproblem gets computed multiple times.
  • Best Case: For ( k=0 ), ( k=n ), or ( k=1 ), we hit the base cases instantly—no recursion needed. Time complexity here is ( O(1) ).
  • General Case: Since ( C(n,k) = C(n, n-k) ), the amount of redundant work depends on the smaller of k and n-k. So time complexity simplifies to ( O(2^{\text{min}(k, n-k)}) ).

For your example with ( n=61, k=55 ), this is equivalent to calculating ( C(61,6) )—which is way more efficient than ( C(61,30) ), but still exponential under the hood.


Space Complexity

Space complexity is driven entirely by the depth of the recursive call stack:

  • Each recursive call adds a new frame to Java's call stack. The maximum depth of this stack is the number of steps needed to reach a base case. For ( C(n,k) ), that's either the steps to get to ( C(n-k, 0) ) or ( C(k,k) ), which is at most n steps. So space complexity is ( O(n) ) in the worst case.
  • There's no extra memory used for caches or data structures here—just the stack space for recursive calls.

Quick Optimization Note

The reason this code is slow for larger n/k is that it doesn't cache already computed results. If you add memoization (like a 2D array or hash map to store ( C(n',k') ) values once calculated), you can drop the time complexity to ( O(nk) )—this would drastically reduce the value of globalhitsToThisMethod by eliminating redundant work.

内容的提问来源于stack exchange,提问作者Aditya Goel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:39:29