找不到任何方法的 StackOverflowError

StackOverflowError In Finding No of Ways

您好,我正在尝试为问题陈述编写 Java 代码:

找不出给m个成员分配n个硬币的方法,其中一个成员是队长(分发者)。每个成员一次可以拿走 1 个硬币,并将其传递给包括队长在内的其他成员。船长不能拥有第一枚硬币。但是,当只剩下一枚硬币时,应该将硬币交给船长。这有多少种可能?

我绑了这个。但是得到WhosebugError。请帮助。

这里我开始调用 solve(1,n)

private static int solve(int r, int n)
    {
        int count = 0;
        if(n==2 && r!=1)
        {
            return 1;
        }
        if(n==2 && r==1)
        {
            return 2;
        }
        for(int i=1;i<=m;i++)
        {
            if(r!=i)
            count += solve(i,--n);  
        }
            return count;
    }

堆栈跟踪

Exception in thread "main" java.lang.WhosebugError
    at NoPrey.solve(NoPrey.java:50)
    at NoPrey.solve(NoPrey.java:62)
    at NoPrey.solve(NoPrey.java:62)
    at NoPrey.solve(NoPrey.java:62)
    at NoPrey.solve(NoPrey.java:62)
    at NoPrey.solve(NoPrey.java:62)
    at NoPrey.solve(NoPrey.java:62)
    at NoPrey.solve(NoPrey.java:62)
    at NoPrey.solve(NoPrey.java:62)
    at NoPrey.solve(NoPrey.java:62)
    at NoPrey.solve(NoPrey.java:62)
    at NoPrey.solve(NoPrey.java:62)
    at NoPrey.solve(NoPrey.java:62)
    at NoPrey.solve(NoPrey.java:62)
    at NoPrey.solve(NoPrey.java:62)
    at NoPrey.solve(NoPrey.java:62)
    at NoPrey.solve(NoPrey.java:62)
    at NoPrey.solve(NoPrey.java:62)
    at NoPrey.solve(NoPrey.java:62)
    at NoPrey.solve(NoPrey.java:62)
    at NoPrey.solve(NoPrey.java:62)
    at NoPrey.solve(NoPrey.java:62)
    at NoPrey.solve(NoPrey.java:62)
    at NoPrey.solve(NoPrey.java:62)
    at NoPrey.solve(NoPrey.java:62)
    at NoPrey.solve(NoPrey.java:62)
    at NoPrey.solve(NoPrey.java:

这只是为了帮助您理解错误。

发生这种情况是因为 n 的值变为负值。只需将 System.out.println(r + "\t\t" + n); 放在方法的开头,然后再 运行 。 n=4 m=3r=1.

的初始值
public static void main(String[] args) throws FileNotFoundException {
  solve(1, 4);
}

private static int solve(int r, int n) {
  System.out.println(r + "\t\t" + n);
  // rest of the code same.

错误前的输出:
1 4 2 3 1 2 3 1 1 0 2 -1 1 -2 2 -3 1 -4 2 -5 1 -6 2 -7 1 -8