动态规划的题目
1 class ColorfulRoad: 2 def getMin(self, road): 3 a = [None] * len(road) 4 a[0] = 0 5 for i in range(0, len(road)-1): 6 if a[i] != None: 7 for j in range(i+1, len(road)): 8 if self.judgeValid(road[i], road[j]): 9 cost = a[i] + (j-i) ** 2 10 if a[j] == None: 11 a[j] = cost 12 else: 13 a[j] = min(a[j], cost) 14 15 if a[len(road)-1] == None: 16 return -1 17 else: 18 return a[len(road)-1] 19 20 def judgeValid(self, fromch, toch): 21 step = ['R', 'G', 'B'] 22 i = step.index(fromch) 23 return toch == step[(1+i)%3] 24 25 26 # test 27 o = ColorfulRoad() 28 29 30 # test case 31 assert(o.getMin('RGGGB') == 8) 32 33 print('ok') 34 35