1. 程式人生 > >動態規劃實現鋼條切割問題

動態規劃實現鋼條切割問題

[] pri turn 計算 ring length pub clas 自頂向下

 1 /**
 2  * 動態規劃實現實現鋼條切割問題
 3  */
 4 public class Test1 {
 5 
 6     static int[] result = {0,0,0,0,0,0,0,0,0,0,0};
 7     static int[] s = {0,0,0,0,0,0,0,0,0,0,0};
 8     
 9     public static void main(String[] args) {
10         int[] arr = {0,1,5,8,9,10,17,17,20,24,30};
11         /*
12         System.out.println("自頂向下結果");
13 for (int i = 0; i < arr.length; i++) { 14 System.out.print("r"+ i +"=" + UpDown(i, arr)+"; "); 15 } 16 */ 17 /* 18 System.out.println("自底向上結果"); 19 for (int i = 0; i < arr.length; i++) { 20 System.out.print("r"+ i +"=" + DownUp(i, arr)+"; ");
21 } 22 */ 23 } 24 25 /** 26 * 自頂向下實現 27 */ 28 static int UpDown(int num, int[] arr) { 29 if(num == 0) return 0; 30 if(result[num] != 0) return result[num]; 31 32 int temp = 0; 33 for (int i = 1; i < num+1; i++) { 34 int
max = arr[i] + UpDown(num-i, arr); 35 if(max > temp) { 36 temp = max; 37 } 38 } 39 result[num] = temp; //將計算的長度為n的鋼條切割的長度用數組保存起來 40 return temp; 41 } 42 43 /** 44 * 自底向上實現 45 */ 46 static int DownUp(int num, int[] arr) { 47 for (int i = 1; i < num + 1; i++) { 48 int temp = 0; 49 for (int j = 1; j <= i; j++) { 50 int max = arr[j] + result[i - j]; 51 if(max > temp) { 52 temp = max; 53 } 54 } 55 result[i] = temp; 56 } 57 return result[num]; 58 } 59 }

動態規劃實現鋼條切割問題