OAmaster
— / 2已做

Let's consider the following infinite sequence:

0, 1, 1, 2, 3, 5, 8, 13, 12, 7, 10, 8, 9, ...

The 0th element is 0 and the 1st element is 1. The successive elements are defined recursively: each of them is the sum of the separate digits of the two previous elements.

Write int solution(int N) returning the N-th element.

Example: N = 2 → 1.

解法

从 2 迭代到 N,每步把前两项各自的数位和相加。复杂度 O(N · log V)

def solution(N: int) -> int:
    if N == 0:
        return 0
    if N == 1:
        return 1
    a, b = 0, 1
    for _ in range(2, N + 1):
        s = sum(int(c) for c in str(a)) + sum(int(c) for c in str(b))
        a, b = b, s
    return b
class Solution {
    public int solution(int N) {
        if (N == 0) return 0;
        if (N == 1) return 1;
        int a = 0, b = 1;
        for (int i = 2; i <= N; i++) {
            int s = digitSum(a) + digitSum(b);
            a = b; b = s;
        }
        return b;
    }
    private int digitSum(int x) {
        int s = 0;
        while (x > 0) { s += x % 10; x /= 10; }
        return s;
    }
}
int digitSum(int x) {
 int s = 0;
 while (x > 0) { s += x % 10; x /= 10; }
 return s;
}

int solution(int N) {
 if (N == 0) return 0;
 if (N == 1) return 1;
 int a = 0, b = 1;
 for (int i = 2; i <= N; i++) {
 int s = digitSum(a) + digitSum(b);
 a = b; b = s;
 }
 return b;
}

There is a board with N cells (numbered from 0 to N−1) arranged in a row. The board is described by an array points and a string tokens, both of length N. The K-th letter of tokens is either 'T' or 'E', indicating whether the K-th cell contains a token or is empty.

If the K-th cell contains a token, we score the number of points in points[K]. Additionally, we score another point for every pair of adjacent cells with tokens. What is the total number of points scored?

Examples:

  • points = [3,2,1,2,2], tokens = "ETTTE" → 7
  • points = [2,2,2,2], tokens = "TTTT" → 11

Constraints

1 ≤ N ≤ 100, 1 ≤ points[i] ≤ 1000, tokens[i] ∈ {E, T}.

Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁
Pro 会员

解锁全部 1 道题的解法

题面你已经看到了 — 解法 + 三语代码 + 复杂度推导 + 边界讨论, Pro 解锁.

Pro 解锁全部
  • 📚1000+ 道真实北美 OA, Python / Java / C++ 三语题解
  • 📊个人 dashboard + 进度可视化 + 14 天活跃图
  • 📝题目笔记跨设备同步 + 个人复盘库
  • 🔓随时取消下次续费, Stripe Customer Portal 自助管理
$12/月($98/年, 一次付清省 32%)

≈ 北美 SWE 工资 10 分钟 · LeetCode Premium $35/月 的 23%