递归求“反转串”“杨辉三角”“斐波那契数”

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));
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值