1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| public void CutTest() { int n = 9; ArrayList<Integer> solution = new ArrayList<Integer>(); int[] price = new int[] { 0, 1, 5, 8, 9, 10, 17, 17, 20, 24, 30 }; System.out.println("Solution: "); System.out.println("The best price is: " + RodCut(solution, price, n)); }
public int RodCut(ArrayList<Integer> solution, int[] price, int n) { if (n == 0) { System.out.println(solution.toString()); return 0; } else { int q = Integer.MIN_VALUE; for (int i = 1; i <= n; i++) { if (i < price.length) { if (solution.isEmpty() || (!solution.isEmpty() && solution.get(solution.size() - 1) <= i)) { solution.add(i); q = Math.max(q, price[i] + RodCut(solution, price, n - i)); solution.remove(solution.size() - 1); } } } return q; } }
|