动态规划实现钢条切割问题
package atguigu. suanfa. 动态规划;
public class CutRod {
static int Max ( int i, int j) {
return i > j ? i : j;
}
static int cutRod ( int p[ ] , int n) {
if ( n == 0 ) {
return 0 ;
}
int q = - 1 ;
for ( int i = 1 ; i <= n; i++ ) {
q = Max ( q, p[ i] + cutRod ( p, n - i) ) ;
}
return q;
}
static int [ ] result = { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } ;
static int [ ] s = { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } ;
static int UpDown ( int num, int [ ] arr) {
if ( num == 0 ) return 0 ;
if ( result[ num] != 0 ) return result[ num] ;
int temp = 0 ;
for ( int i = 1 ; i < num + 1 ; i++ ) {
temp = Math. max ( temp, arr[ i] + UpDown ( num - i, arr) ) ;
}
result[ num] = temp;
return temp;
}
static int DownUp ( int num, int [ ] arr) {
for ( int i = 1 ; i < num + 1 ; i++ ) {
int temp = 0 ;
for ( int j = 1 ; j <= i; j++ ) {
temp = Math. max ( temp, arr[ j] + result[ i - j] ) ;
}
result[ i] = temp;
}
return result[ num] ;
}
public static void main ( String[ ] args) {
int [ ] priceShuZu = new int [ ] { 0 , 1 , 5 , 8 , 9 , 10 , 17 , 17 , 20 , 24 , 30 } ;
int f = cutRod ( priceShuZu, 10 ) ;
System. out. println ( f) ;
int f2 = UpDown ( 10 , priceShuZu) ;
System. out. println ( f2) ;
int i = DownUp ( 10 , priceShuZu) ;
System. out. println ( i) ;
}
}