(HW)rod cutting(Java)

 1 public class test
 2 {
 3     public static void main(String[] args)
 4     {
 5         Scanner input = new Scanner(System.in);
 6         int n = input.nextInt();
 7         //第一个位置不使用
 8         int[] prices = new int[] {0,1,5,8,9,10,17,17,20,24,30};
 9         int[] r = new int[n + 1];
10         for(int i = 0; i < r.length; i++)
11             r[i] = Integer.MIN_VALUE;
12         System.out.println(MaxProfit(n, prices, r));
13     }    
14     
15     //recursion
16     public static int MaxProfit(int n, int[] prices, int[] r)
17     {
18         if(n == 0)
19             return 0;
20         
21         int tmpMax = Integer.MIN_VALUE;
22         for(int i = 1; i <= n; i++)
23         {
24             //避免重复计算
25             if(r[n - i] == Integer.MIN_VALUE)
26                 r[n - i] = MaxProfit(n - i, prices, r);
27             tmpMax = Math.max(tmpMax, prices[i] + r[n - i]);
28         }
29         
30         return tmpMax;
31     }
32     
33     //iteration 时间复杂度: O(N^2)
34     public static int MaxProfit(int n, int[] prices, int[] r)
35     {
36         r[0] = 0;
37         for(int i = 1; i <= n; i++)
38             for(int j = 1; j <= i; j++)
39                 r[i] = Math.max(r[i], prices[j] + r[i - j]);
40         
41         return r[n];
42     }
43 }

 

转载于:https://www.cnblogs.com/Huayra/p/10957266.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值