![]() |
VOOZH | about |
A Padovan Sequence is a sequence similar to Fibonacci sequence which is represented by the following recurrence relation:
P(n) = P(n - 2) + P(n - 3)
P(0) = P(1) = P(2) = 1
First few terms of the sequence are 1, 1, 1, 2, 2, 3, 4, 5, 7, 9, 12, 16, 21, 28, 37,..... Spiral of equilateral triangles with side lengths which follow the Padovan sequence.
Given a number n, find the nth number in the Padovan Sequence. Since the output may be too large, compute the answer modulo 10^9 + 7.
Examples:
Input: n = 4
Output: 2
Explanation: P(4) = P(2) + P(1) = 1 + 1 = 2Input: n = 7
Output: 5
Explanation:
P(7) = P(5) + P(4) = P(3) + P(2) + P(2) + P(1)
= P(1) + P(0) + 1 + 1 + 1 = 1 + 1 + 1 + 1 + 1 = 5
Table of Content
5
A naive recursive approach recalculates the same subproblems many times, leading to exponential time complexity. Dynamic Programming avoids this by storing already computed values in a table (dp array) and building the answer in a bottom-up manner. This converts the solution into a linear time process by ensuring each state is computed only once.
Consider the following dry run for better understanding: n = 10
Final answer : 12
5