Hedvig Interview - Count of number with no consecutive 1's

Given integer n, find the number of different binary strings of size n where there are no consecutive 1's.Eg: If n is 2, valid strings are 00, 01, 10. You should return 3.

假设f(n, k)是第n位上为k的数字的个数

无论第n-1位是0还是1,第n位都能取0,故有:
f(n, 0) = f(n-1, 0) + f(n-1, 1)

而只有在第n-1位取0时,第n位才能取1,即:
f(n, 1) = f(n-1, 0)

n位bit能表示的数目总和是:
f(n) = f(n, 0) + f(n, 1) = [f(n-1, 0) + f(n-1, 1)] + f(n-1, 0) = f(n-1) + [f(n-2, 0) + f(n-2, 1)] = f(n-1) + f(n-2)

所以,f(n)就是一个Fibonacci数。简单迭代即可得到。

public static int noConsucetive1(int n) {
	if(n <= 0) return 0;
	int[] f1 = new int[n+1];
	int[] f0 = new int[n+1];
	f0[1] = f1[1] = 1;
	for(int i=2; i<=n; i++) {
		f0[i] = f0[i-1] + f1[i-1];
		f1[i] = f0[i-1];
	}
	return f0[n]+f1[n];
}
public static int noConsucetive1(int n) {
	if(n <= 0) return 0;
	int[] f = new int[n+1];
	f[0] = 1; f[1] = 2;
	for(int i=2; i<=n; i++) {
		f[i] = f[i-1] + f[i-2];
	}
	return f[n];
}

猜你喜欢

转载自yuanhsh.iteye.com/blog/2229343
今日推荐