Java—计算题
Description
一个简单的计算,你需要计算f(m,n),其定义如下:
当m=1时,f(m,n)=n;
当n=1时,f(m,n)=m;
当m>1,n>1时,f(m,n)= f(m-1,n)+ f(m,n-1)
Input
第一行包含一个整数T(1<=T<=100),表示下面的数据组数。
以下T行,其中每组数据有两个整数m,n(1<=m,n<=2000),中间用空格隔开。
Output
对每组输入数据,你需要计算出f(m,n),并输出。每个结果占一行。
Sample
Input
2
1 1
2 3
Output
1
7
import java.util.Scanner;
public class Main {
public static int f(int m, int n) {
int y;
if (m == 1)
y = n;
else if (n == 1)
y = m;
else
y = f(m - 1, n) + f(m, n - 1);
return y;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner reader = new Scanner(System.in);
int t, i;
int m, n;
while (reader.hasNext()) {
t = reader.nextInt();
for (i = 0; i < t; i++) {
m = reader.nextInt();
n = reader.nextInt();
System.out.print(f(m, n));
if (i != t - 1)
System.out.println();
}
}
}
}
递归计算函数f(m,n)的Java实现
这是一个关于使用Java编程解决递归计算问题的示例。给定一个函数f(m,n),当m=1时返回n,n=1时返回m,否则返回f(m-1,n) + f(m,n-1)。程序读取输入的测试用例数量和m、n值,通过递归计算并输出f(m,n)的结果。示例输入为2组数据,分别是(11,23)和(1,7),对应的输出为1和7。
745

被折叠的 条评论
为什么被折叠?



