简体   繁体   English

如何编写一个接受2个整数的递归置换方法

[英]How to write a recursive permutation method that accepts 2 ints

I need to write a method that does n!/(nr)!. 我需要编写一个执行n!/(nr)!的方法。 This would be easy to do in a for loop but I can't figure it out recursively. 在for循环中这样做很容易,但是我无法递归地解决。 Here is my code so far. 到目前为止,这是我的代码。

public static int permut(int n, int r) {
    if (r == 0) {
        return 0;
    } else if (r==1){
        return n;
    } else {    
        return n * permut(n, r-1)/permut(n,r-1);
    }
}

I am not sure how to setup the return. 我不确定如何设置退货。

Essentially, you can think of this the same as a normal factorial, accept that you decrement n and r each recursion and stop when r == 1 instead of n == 1 . 本质上,您可以将其与普通阶乘相同,接受递减nr并在r == 1而不是n == 1时停止。

public static int permut(int n, int r){
    if(r == 1) return n;
    return n*permut(n-1, r-1);
}

So if n = 10 and r = 3 , you need 10!/(10-3)! 因此,如果n = 10r = 3 ,则需要10!/(10-3)! or 10*9*8 , and the program will give: 10*9*8 ,程序将给出:

n = 10, r = 3, val = 10
n = 9,  r = 2, val = 10*9
n = 8,  r = 1, val = 10*9*8

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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