I tried to solve the question that calculates the number in the array of kth row, nth column. As you can see in the figure below, the value of the first row, nth column is n. Then, array[k][n] is the sum of values across from array[k-1][1] to array[k-1][n]. (I can use only basic python tools, cannot use Numpy or other packages in this problem)
At first, I tried to solve the problem by using the recursive function as follows.
def n_family(k, n):
if k == 0:
return n
elif n == 1:
return 1
else:
return n_family(k-1,n) + n_family(k,n-1)
k = int(input())
n = int(input())
print(n_family(k, n))
However, I failed because the code spent too much when k > 12 and n > 12. Then, I used the code below
k = int(input())
n = int(input())
apt = [[j+1 if i == 0 else 0 for j in range(14) ] for i in range(k+1)] #max(n) is 14
for floor in range(1,k+1):
apt[floor][0] = 1
for room in range(1,14):
apt[floor][room] += (apt[floor][room-1] + apt[floor-1][room])
print(apt[k][n-1])
I wonder why the second code spent less time. And I want to ask if using recursive function inefficient in python always? Or This situation is just a specific case?