|
| 1 | +packageAlgorithms.algorithm.dp; |
| 2 | + |
| 3 | +importjava.util.ArrayList; |
| 4 | + |
| 5 | +publicclassMinAdjustmentCost_Class { |
| 6 | +publicstaticvoidmain(String[]strs) { |
| 7 | +ArrayList<Integer>A =newArrayList<Integer>(); |
| 8 | +A.add(1); |
| 9 | +A.add(4); |
| 10 | +A.add(2); |
| 11 | +A.add(3); |
| 12 | + |
| 13 | +System.out.println(MinAdjustmentCost(A,1)); |
| 14 | + } |
| 15 | + |
| 16 | +/** |
| 17 | + * @param A: An integer array. |
| 18 | + * @param target: An integer. |
| 19 | + */ |
| 20 | +publicstaticintMinAdjustmentCost(ArrayList<Integer>A,inttarget) { |
| 21 | +// write your code here |
| 22 | +if (A ==null) { |
| 23 | +return0; |
| 24 | + } |
| 25 | + |
| 26 | +returnrec(A,newArrayList<Integer>(A),target,0); |
| 27 | + } |
| 28 | + |
| 29 | +publicstaticintrec(ArrayList<Integer>A,ArrayList<Integer>B,inttarget,intindex) { |
| 30 | +intlen =A.size(); |
| 31 | +if (index >=len) { |
| 32 | +// The index is out of range. |
| 33 | +return0; |
| 34 | + } |
| 35 | + |
| 36 | +intdif =0; |
| 37 | + |
| 38 | +intmin =Integer.MAX_VALUE; |
| 39 | + |
| 40 | +// If this is the first element, it can be from 1 to 100; |
| 41 | +for (inti =0;i <=100;i++) { |
| 42 | +if (index !=0 &&Math.abs(i -B.get(index -1)) >target) { |
| 43 | +continue; |
| 44 | + } |
| 45 | + |
| 46 | +B.set(index,i); |
| 47 | +dif =Math.abs(i -A.get(index)); |
| 48 | +dif +=rec(A,B,target,index +1); |
| 49 | +min =Math.min(min,dif); |
| 50 | + |
| 51 | +// 回溯 |
| 52 | +B.set(index,A.get(index)); |
| 53 | + } |
| 54 | + |
| 55 | +returnmin; |
| 56 | + } |
| 57 | + |
| 58 | +} |