[英]find Number of ways to get total of 17cents (for example) using 1,5,10,25,50 cents
為什么我會收到堆棧溢出錯誤,在我開始使用動態編程之前,我試圖以遞歸方式解決這個問題。在硬幣方法中,“a”是保存硬幣的數組,sum 是我想要的總數(例如 17),我表示我所在數組的索引
import java.util.*;
public class dp2 {//RECURSIVE WAY THEN OPTIMIZE TO DP
public static int coins (int [] a, int sum,int i){
if (sum==0)
return 1;
else if (i==a.length){
return 0;
}
else if (i>a.length&&sum<a[i]){
return coins(a,sum,i++);
}
else {
return coins(a,sum-a[i],i++)+coins(a,sum-a[i],i);
}
}
public static void main (String [] args ){
Scanner sc = new Scanner (System.in);
while (sc.hasNext()){
int x = sc.nextInt();
int y=x;
int [] a ={1,5,10,25,50};
int w = coins(a,y,0);
System.out.println("There are " +w+ " ways to produce "+x + " coins change.");
}
}
}
你有無限循環的問題。
首先檢查,你想返回什么,因為實際上你只能返回1或0。那么,其他條件在哪里? 示例: i == a.length - 1 或 sum < 0 ? 我想,你想返回總和。
接下來,如果你把例子17,那么從陣列中選擇女巫硬幣的機制在哪里可以選擇?
接下來,請更改return coins(a,sum-a[i],++i)+coins(a,sum-a[i],i);
,因為在你的代碼中i總是 0
所以,也許對你來說是很好的例子代碼:
class dp2 {//RECURSIVE WAY THEN OPTIMIZE TO DP
public static int coins (int [] a, int sum,int i){
if (sum==0)
return 1;
else if (i==a.length){
return 0;
}else if(i + 1 == a.length || sum < 0 || sum - a[i] < 0){ //Your break condition ?
return sum;
}
else if (i>a.length&&sum<a[i]){
return coins(a,sum,i++);
}
else {
return coins(a,sum-a[i],++i)+coins(a,sum-a[i],i);
}
}
public static void main (String [] args ){
Scanner sc = new Scanner (System.in);
while (sc.hasNext()){
int x = sc.nextInt();
int y=x;
int [] a ={1,5,10,25,50};
int w = coins(a,y,0);
System.out.println("There are " +w+ " ways to produce "+x + " coins change.");
}
}
}
我在您的代碼中添加了一條語句,位於第 4 行:
System.out.println(sum + ", " + i);
給輸入27,輸出是:
27, 0
26, 0
25, 0
.... decreasing by one each time...
3, 0
2, 0
1, 0
0, 0
-4, 1
-9, 1
-14, 1
然后它永遠不會停止,因為您不檢查sum < 0
。
你應該能夠從那里弄清楚...... println
:世界上最輕量級的調試器:-)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.