public class Main{
// 求一个串的“反转串”
public static String f(String s) {
if (s.length()<=1) return s;
return f(s.substring(1)) + s.charAt(0);
}
public static void main(String[] args) {
String s = "abcd";
System.out.println(f(s));
}
}
public class Main{
//杨辉三角的第m层的第n个元素,m和n都从0开始
public static int f(int m, int n) {
if (n == 0 || m==n) return 1;
return f(m-1, n) + f(m-1, n-1);
}
public static void main(String[] args) {
int level = 5;
for (int i=0; i<=level; i++) {
System.out.print(f(level, i) + " ");
}
}
}
思路 : 将杨辉三角整理成这样:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
可以看出,第m行第n个元素等于他上方元素加上他左上方元素,因此递推公式很容易写出。
public class Main{
//求斐波那契数
public static int f(int n) {
if (n==1 || n==2) return 1;
return f(n-1) + f(n-2);
}
public static void main(String[] args) {
int n = 10;
System.out.println(f(n));
}
}