From 9fa578d4b5c299fe839c474a4f6c65f9e5f85472 Mon Sep 17 00:00:00 2001 From: Alexander Pantyukhin Date: Fri, 3 Feb 2023 05:58:32 +0400 Subject: [PATCH] feat: add N-th Tribonacci number (#1202) * add leetcode n-th Tribonacci number * updating DIRECTORY.md * updating DIRECTORY.md --------- Co-authored-by: github-actions[bot] --- leetcode/DIRECTORY.md | 1 + leetcode/src/1137.c | 29 +++++++++++++++++++++++++++++ 2 files changed, 30 insertions(+) create mode 100644 leetcode/src/1137.c diff --git a/leetcode/DIRECTORY.md b/leetcode/DIRECTORY.md index f9a4f8d7..5d1843f7 100644 --- a/leetcode/DIRECTORY.md +++ b/leetcode/DIRECTORY.md @@ -119,6 +119,7 @@ | 1019 | [Next Greater Node In Linked List](https://leetcode.com/problems/next-greater-node-in-linked-list) | [C](./src/1019.c) | Medium | | 1026 | [Maximum Difference Between Node and Ancestor](https://leetcode.com/problems/maximum-difference-between-node-and-ancestor) | [C](./src/1026.c) | Medium | | 1089 | [Duplicate Zeros](https://leetcode.com/problems/duplicate-zeros) | [C](./src/1089.c) | Easy | +| 1137 | [N-th Tribonacci Number](https://leetcode.com/problems/n-th-tribonacci-number) | [C](./src/1137.c) | Easy | | 1147 | [Longest Chunked Palindrome Decomposition](https://leetcode.com/problems/longest-chunked-palindrome-decomposition) | [C](./src/1147.c) | Hard | | 1184 | [Distance Between Bus Stops](https://leetcode.com/problems/distance-between-bus-stops) | [C](./src/1184.c) | Easy | | 1189 | [Maximum Number of Balloons](https://leetcode.com/problems/maximum-number-of-balloons) | [C](./src/1189.c) | Easy | diff --git a/leetcode/src/1137.c b/leetcode/src/1137.c new file mode 100644 index 00000000..0bb7fdc3 --- /dev/null +++ b/leetcode/src/1137.c @@ -0,0 +1,29 @@ +// Dynamic Programming +// Runtime: O(n) +// Space: O(1) +int tribonacci(int n){ + int t0 = 0; + int t1 = 1; + int t2 = 1; + + if (n == 0) { + return t0; + } + + if (n == 1){ + return t1; + } + + if (n == 2){ + return t2; + } + + for (int i = 0; i < n - 2; i++){ + int nextT = t0 + t1 + t2; + t0 = t1; + t1 = t2; + t2 = nextT; + } + + return t2; +}