Given the mobile numeric keypad. You can only press buttons that are up, left, right, or down to the current button. You are not allowed to press bottom row corner buttons (i.e. * and # ). Given a number N, the task is to find out the number of possible numbers of the given length.
Example 1:
Input: 1
Output: 10
Explanation: Number of possible numbers
would be 10 (0, 1, 2, 3, …., 9)
Example 2:
Input:N = 2
Output:36
Explanation: Possible numbers: 00, 08, 11,
12, 14, 22, 21, 23, 25 and so on.
If we start with 0, valid numbers
will be 00, 08 (count: 2)
If we start with 1, valid numbers
will be 11, 12, 14 (count: 3)
If we start with 2, valid numbers
will be 22, 21, 23,25 (count: 4)
If we start with 3, valid numbers
will be 33, 32, 36 (count: 3)
If we start with 4, valid numbers
will be 44,41,45,47 (count: 4)
If we start with 5, valid numbers
will be 55,54,52,56,58 (count: 5)
and so on..
Mobile numeric keypad | Practice | GeeksforGeeks
class Solution{
public:
long long getCount(int N)
{
vector<vector<int>> v(10);
v[0] = {0,8};
v[1] = {1,2,4};
v[2] = {2,1,3,5};
v[3] = {3,2,6};
v[4] = {4,1,5,7};
v[5] = {4,2,5,6,8};
v[6] = {6,3,5,9};
v[7] = {7,4,8};
v[8] = {7,8,5,9,0};
v[9] = {9,8,6};
long long int dp[N+1][10];
for(int i=0;i<=N;i++)
{
for(int j=0;j<=9;j++)
{
if(i==0||i==1)
dp[i][j] = i;
else
{
long long int sum = 0;
for(int ele:v[j])
sum+=dp[i-1][ele];
dp[i][j] = sum;
}
}
}
long long int res = 0;
for(long long int ele:dp[N])
res+=ele;
return res;
}
};