Given n, find count of n digit Stepping numbers. A number is called stepping number if all adjacent digits have an absolute difference of 1. 321 is a Stepping Number while 421 is not.
Input : 2 Output : 17 Explanation: The numbers are 10, 12, 21, 23, 32, 34, 43, 45, 54, 56, 65, 67, 76, 78, 87, 89, 98. Input : 1 Output : 10 Explanation: the numbers are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.
A naive approach is to run a loop for all n digit numbers and check for every number if it is Stepping.
An efficient approach is to use dynamic programming.
In dp[i][j], i denotes number of digits and j denotes last digit. // If there is only one digit if (i == 1) dp(i, j) = 1; // If last digit is 0. if (j == 0) dp(i, j) = dp(i-1, j+1) // If last digit is 9 else if (j == 9) dp(i, j) = dp(i-1, j-1) // If last digit is neither 0 // nor 9. else dp(i, j) = dp(i-1, j-1) + dp(i-1, j+1) Result is ∑dp(n, j) where j varies from 1 to 9.
Time Complexity: O(n)
Auxiliary Space: O(n)
- Multistage Graph (Shortest Path)
- Number of ordered pairs such that (Ai & Aj) = 0
- Minimum cost to make two strings identical by deleting the digits
- Find Harmonic mean using Arithmetic mean and Geometric mean
- Deserium Number
- Largest number by which given 3 numbers should be divided such that they leaves same remainder
- Print Longest Palindromic Subsequence
- Program for Bridge and Torch problem
- Number of substrings divisible by 8 but not by 3
- Dynamic Programming | Building Bridges
- Sum of Fibonacci Numbers
- Total number of non-decreasing numbers with n digits
- Minimum insertions to form a palindrome | DP-28
- Optimal Binary Search Tree | DP-24
- Word Wrap Problem | DP-19
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.