leetcode - Jump Game II
2013-04-21 11:33 张汉生 阅读(158) 评论(0) 编辑 收藏 举报题目描述:点击此处
这道题的优化需要好好想想,自己想了半天才想出来,真笨。
1 class Solution { 2 public: 3 int jump(int A[], int n) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 if (n<=0) 7 return true; 8 int *flag = new int[n]; 9 int *index = new int[n]; 10 index[n-1] = 1000000000; 11 flag[n-1] = 0; 12 int i, j; 13 for (i=0; i<n-1; i++){ 14 flag[i] = 1000000000; 15 index[i] = 1000000000; 16 } 17 for (i=n-2; i>=0; i--){ 18 for (j=1; j<=A[i] && i+j<n;){ 19 if (index[i+j]<=i+A[i]){ 20 if (flag[i] > flag[i+j]){ 21 flag[i] = flag[i+j]; 22 index[i] = index[i+j]; 23 } 24 } 25 else if (flag[i]>flag[i+j]+1){ 26 flag[i] = flag[i+j] + 1; 27 index[i] = i+j; 28 } 29 if (A[i+j]>0) 30 j += A[i+j]; 31 else j++; 32 } 33 } 34 int rlt = flag[0]; 35 delete []index; 36 delete []flag; 37 return rlt; 38 } 39 };