Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit41a5c04

Browse files
committed
min cost
1 parentc14d476 commit41a5c04

File tree

1 file changed

+68
-1
lines changed

1 file changed

+68
-1
lines changed

‎algorithm/dp/MinAdjustmentCost_Class.java

Lines changed: 68 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ public static void main(String[] strs) {
1717
* @param A: An integer array.
1818
* @param target: An integer.
1919
*/
20-
publicstaticintMinAdjustmentCost(ArrayList<Integer>A,inttarget) {
20+
publicstaticintMinAdjustmentCost1(ArrayList<Integer>A,inttarget) {
2121
// write your code here
2222
if (A ==null) {
2323
return0;
@@ -26,6 +26,10 @@ public static int MinAdjustmentCost(ArrayList<Integer> A, int target) {
2626
returnrec(A,newArrayList<Integer>(A),target,0);
2727
}
2828

29+
/*
30+
* SOL 1:
31+
* 最普通的递归方法。
32+
* */
2933
publicstaticintrec(ArrayList<Integer>A,ArrayList<Integer>B,inttarget,intindex) {
3034
intlen =A.size();
3135
if (index >=len) {
@@ -54,5 +58,68 @@ public static int rec(ArrayList<Integer> A, ArrayList<Integer> B, int target, in
5458

5559
returnmin;
5660
}
61+
62+
/*
63+
* 递归2:
64+
* Rec + memory.
65+
* */
66+
/**
67+
* @param A: An integer array.
68+
* @param target: An integer.
69+
*/
70+
publicstaticintMinAdjustmentCost(ArrayList<Integer>A,inttarget) {
71+
// write your code here
72+
if (A ==null ||A.size() ==0) {
73+
return0;
74+
}
75+
76+
int[][]M =newint[A.size()][100];
77+
for (inti =0;i <A.size();i++) {
78+
for (intj =0;j <100;j++) {
79+
M[i][j] =Integer.MAX_VALUE;
80+
}
81+
}
82+
83+
returnrec2(A,newArrayList<Integer>(A),target,0,M);
84+
}
85+
86+
publicstaticintrec2(ArrayList<Integer>A,ArrayList<Integer>B,inttarget,intindex,
87+
int[][]M) {
88+
intlen =A.size();
89+
if (index >=len) {
90+
// The index is out of range.
91+
return0;
92+
}
93+
94+
intdif =0;
95+
intmin =Integer.MAX_VALUE;
96+
97+
// If this is the first element, it can be from 1 to 100;
98+
for (inti =1;i <=100;i++) {
99+
if (index !=0 &&Math.abs(i -B.get(index -1)) >target) {
100+
continue;
101+
}
102+
103+
if (M[index][i -1] !=Integer.MAX_VALUE) {
104+
dif =M[index][i -1];
105+
min =Math.min(min,dif);
106+
continue;
107+
}
108+
109+
B.set(index,i);
110+
dif =Math.abs(i -A.get(index));
111+
dif +=rec2(A,B,target,index +1,M);
112+
113+
min =Math.min(min,dif);
114+
115+
// Record the result.
116+
M[index][i -1] =dif;
117+
118+
// 回溯
119+
B.set(index,A.get(index));
120+
}
121+
122+
returnmin;
123+
}
57124

58125
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp