问:同一平面内n条直线最多几个交点?
1条线是0,2条线是1,3条线是3......
很简单,用递归即可解决,不需要用数学知识。
解:
public class Main {
static int fun(int n) {
if (n == 1)
return 0;
return fun(n - 1) + (n - 1);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
System.out.println(fun(n));
}
}
问:求串的翻转串(不用for循环)
输入:abc
输出:cba
解:
public class Main {
static String fun(String s) {
if (s.length() <= 1)
return s;
// s.sbustring(1)可以返回从s串从下标为1开始的子串
// 每次递归加上s.charAt(0)就可以把s最开头的字符放在最后面输出
return fun(s.substring(1)) + s.charAt(0);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String s = in.next();
System.out.println(fun(s));
}
}
问:
小明参加了学校的趣味运动会,其中的一个项目是:跳格子。 地上画着一些格子,每个格子里写一个字,如下所示:(也可参见下图) 从我做起振 我做起振兴 做起振兴中 起振兴中华 比赛时,先站在左上角的写着“从”字的格子里,可以横向或纵向跳到相邻的格子里,但不能跳到对角的格子或其它位置。一直要跳到“华”字结束。 要求跳过的路线刚好构成“从我做起振兴中华”这句话。 请你帮助小明算一算他一共有多少种可能的跳跃路线呢?
这其实就是问从a点到b点的最近路线有多少种。
解:(答案是35)
public class Main {
// fun方法返回的是当前位置到(1,1)的最短路线的种数
static int fun(int x, int y) {
if (x == 1 || y == 1)
// 到达两条边界其中一条时就算一次,因为那时就只能一路走到头,没有别的走法了
return 1;
return fun(x - 1, y) + fun(x, y - 1);// 向右走和向下走
}
public static void main(String[] args) {
System.out.println(fun(5, 4));
}
}