LeetCode. The Nth Fibonacci Number (Java)

The first type: the recursive formula of Fibonacci sequence is: Fn=Fn-1+Fn-2, where F1=F2=1.
The second type: T0 = 0, T1 = 1, T2 => 1, and under the condition of n >= 0 Tn+3 = Tn + Tn+1 + Tn+2

The last is all, give you the integer n, please return the value of the nth Tebonacci number Tn.

The two are similar, but when setting variables, the second case needs to set one more
. The first case: iteration

public static int fibonacci(int n) {
    
    
	int x1 = 1;
	int x2 = 1;
	int x3 = 0;
	if (n == 1 || n == 2) {
    
    
		return 1;
	} else {
    
    
		while (n - 2 > 0) {
    
    
			x3 = x1 + x2;
			x3 %= 10007;
			x1 = x2 % 10007;
			x2 = x3;
			n--;
		}
		return x3;
	}
}

The second type: iteration

public int tribonacci(int n) {
    
    
	if (n <= 2) {
    
    
		return n == 0 ? 0 : 1;
	}
	int a = 0, b = 1, c = 1, d = 0;
	for (int i = 3; i <= n; i++) {
    
    
		d = a + b + c;
		a = b;
		b = c;
		c = d;
	}
	return c;
}

Recursion:

public int tribonacci(int n) {
    
    
	if (n <= 2) {
    
    
		return n == 0 ? 0 : 1;
	}
	int[] dp = new int[n + 1];
	dp[0] = 0;
	dp[1] = 1;
	dp[2] = 1;
	for (int i = 3; i <= n; i++) {
    
    
		dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3];
	}
	return dp[dp.length - 1];
}

end.

Guess you like

Origin blog.csdn.net/weixin_44998686/article/details/108574324