-7
我對python比較新。當我嘗試執行下面的代碼時,我收到了這個錯誤。我不明白這個錯誤。Python:IndexError:列表索引超出範圍
def coinChange(S,m,n):
dp = [[0 for x in range(m)] for x in range(n+1)]
for i in range(m):
dp[0][i] = 1
for i in range(1,n+1):
for j in range(m):
if i >= S[j]:
dp[i][j] = dp[i-1][j] + dp[i][i-S[j]]
else:
dp[i][j] = dp[i-1][j]
return dp[i][j]
S = [1,3,5]
m = len(S)
n = 11
print(coinChange(S,m,n))
This is the error I'm getting:
Traceback (most recent call last):
File "C:\Users\SaiV\CoinChange.py", line 24, in <module>
print(coinChange(S,m,n))
File "C:\Users\SaiV\CoinChange.py", line 13, in coinChange
dp[i][j] = dp[i-1][j] + dp[i][i-S[j]]
IndexError: list index out of range
代碼應該做什麼?給定值的預期輸出是多少?你正在嘗試在其邊界外的列表上進行迭代。 – CristiFati
當'i = 4'和'j = 0'出現問題時。 'dp [i] [i - S [j]]'轉換爲'dp [4] [3]',第二個索引在它的間隔之外(0,1,2)。 – CristiFati