1. 程式人生 > >動態規劃——Freedom Trail

動態規劃——Freedom Trail

題目:https://leetcode.com/problems/freedom-trail/

額。。。不解釋大意了,題目我也不想寫過程了有點繁瑣,直接給出程式碼:

 1 public int findRotateSteps(String ring, String key) {
 2         int rlen = ring.length();
 3         int klen = key.length();
 4         int[][]dp = new int[klen+1][rlen+1];
 5         int temp = 0,step = 0,diff = 0;
6 for(int i = 0;i<=klen;i++) { 7 for(int j = 1;j<=rlen;j++) 8 if(i==0)dp[i][j] = 0; 9 else dp[i][j] = Integer.MAX_VALUE; 10 } 11 for(int i = 1;i<=klen;i++) { 12 for(int j = 1;j<=rlen;j++) { 13 temp = Integer.MAX_VALUE;
14 if(ring.charAt(j-1)==key.charAt(i-1)) { 15 if(i==1)temp = Math.min(j-1,rlen+1-j); 16 else { 17 for(int k = 1;k<=rlen;k++) 18 if(dp[i-1][k]!=Integer.MAX_VALUE) { 19 diff = Math.abs(j-k);
20 step = Math.min(diff,rlen-diff); 21 temp = Math.min(temp,step+dp[i-1][k]); 22 } 23 } 24 } 25 dp[i][j] = temp; 26 } 27 } 28 /* 29 for(int i = 1;i<=klen;i++) { 30 for(int j = 1;j<=rlen;j++) 31 System.out.print(dp[i][j]+" "); 32 System.out.println(); 33 }*/ 34 int ans = dp[klen][1]; 35 for(int i = 2;i<=rlen;i++) { 36 ans = ans < dp[klen][i]?ans:dp[klen][i]; 37 } 38 return ans+klen; 39 }