标签:== stat print static code 计算 main nbsp 钢条切割
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 }
标签:== stat print static code 计算 main nbsp 钢条切割
原文地址:https://www.cnblogs.com/fsmly/p/10046748.html