@@ -139,36 +139,35 @@ class Solution:
139139``` py
140140class Solution :
141141 def superEggDrop (self , K : int , N : int ) -> int :
142- for i in range (K + 1 ):
143- for j in range (N + 1 ):
144- if i == 1 :
145- dp[i][j] = j
146- if j == 1 or j == 0 :
147- dp[i][j] == j
148- dp[i][j] = j
149- for k in range (1 , j + 1 ):
150- dp[i][j] = min (dp[i][j], max (dp[i - 1 ][k - 1 ] + 1 , dp[i][j - k] + 1 ))
151- return dp[K][N]
142+ dp = [[i for _ in range (K+ 1 )] for i in range (N + 1 )]
143+ for i in range (N + 1 ):
144+ for j in range (1 , K + 1 ):
145+ dp[i][j] = i
146+ if j == 1 :
147+ continue
148+ if i == 1 or i == 0 :
149+ break
150+ for k in range (1 , i + 1 ):
151+ dp[i][j] = min (dp[i][j], max (dp[k - 1 ][j- 1 ] + 1 , dp[i- k][j] + 1 ))
152+ return dp[N][K]
152153```
153154
154155值得注意的是,在这里内外循环的顺序无关紧要,并且内外循坏的顺序对我们写代码来说复杂程度也是类似的,各位客官可以随意调整内外循环的顺序。比如这样也是可以的:
155156
156157``` py
157158class Solution :
158159 def superEggDrop (self , K : int , N : int ) -> int :
159- dp = [[0 ] * (K + 1 ) for _ in range (N + 1 )]
160-
161- for i in range (N + 1 ):
162- for j in range ( K + 1 ):
163- if j == 1 :
164- dp[i][j] = i
165- if i == 1 or i == 0 :
166- dp[i][j] == i
167- dp[i][j] = i
168- for k in range (1 , i + 1 ):
169- dp[i][j] = min (dp[i][j], max (dp[k - 1 ][j - 1 ] + 1 , dp[i - k][j] + 1 ))
170- return dp[N][K]
171- dp = [[0 ] * (N + 1 ) for _ in range (K + 1 )]
160+ dp = [[i for i in range (N+ 1 )] for _ in range (K + 1 )]
161+ for i in range (1 , K + 1 ):
162+ for j in range (N + 1 ):
163+ dp[i][j] = j
164+ if i == 1 :
165+ break
166+ if j == 1 or j == 0 :
167+ continue
168+ for k in range (1 , j + 1 ):
169+ dp[i][j] = min (dp[i][j], max (dp[i - 1 ][k - 1 ] + 1 , dp[i][j - k] + 1 ))
170+ return dp[K][N]
172171```
173172
174173总结一下,上面的解题方法思路是:
0 commit comments