tinycodinglm / cp /cp-10018.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 12)
3c88a0f verified
|
Raw History Blame Contribute Delete
2.18 kB
opencode trace
System You are an expert LeetCode problem solver. You solve problems efficiently with clean code.

You are an expert LeetCode problem solver. You solve problems efficiently with clean code.

User

Problem: Fibonacci Number (Difficulty: Easy)
Tags: Math, Dynamic Programming, Recursion, Memoization

The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,
Given n, calculate F(n).

Example 1:
F(0) = 0, F(1) = 1
F(n) = F(n - 1) + F(n - 2), for n > 1.

Example 2:
Input: n = 2
Output: 1
Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.

Example 3:
Input: n = 3
Output: 2
Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.

Example 4:
Input: n = 4
Output: 3
Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.

Constraints:

  • 0 <= n <= 30
Assistant

Time: O(logn)

Space: O(1)

import itertools

class Solution(object):
def fib(self, N):
"""
:type N: int
:rtype: int
"""
def matrix_expo(A, K):
result = [[int(i==j) for j in range(len(A))]
for i in range(len(A))]
while K:
if K % 2:
result = matrix_mult(result, A)
A = matrix_mult(A, A)
K /= 2
return result

markdown
def matrix_mult(A, B):
        ZB = zip(*B)
        return [[sum(a*b for a, b in itertools.izip(row, col)) \
                 for col in ZB] for row in A]

    T = [[1, 1],
         [1, 0]]
    return matrix_mult([[1, 0]], matrix_expo(T, N))[0][1]  # [a1, a0] * T^N

Time: O(n)

Space: O(1)

class Solution2(object):
def fib(self, N):
"""
:type N: int
:rtype: int
"""
prev, current = 0, 1
for i in range(N):
prev, current = current, prev + current,
return prev