繁体   English   中英

find 使用 1,5,10,25,50 cents 获得总计 17cents 的方法数(例如)

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM