# QUESTION STATEMENT:

Given a string containing digits from `2-9` inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.

A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

Example 1:

`Input: digits = "23"Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]`

Example 2:

`Input: digits = ""Output: []`

Example 3:

`Input: digits = "2"Output: ["a","b","c"]`

Constraints:

• `0 <= digits.length <= 4`
• `digits[i]` is a digit in the range `['2', '9']`.

# SOLUTION:

This question can be easily solved using recursion. we can say (broadly), that recursion generates possible strings by using 1st digit and then solves it for subsequent digits.

For ex:

`// Input345`

Now characters associated with:

`3 - d, e, f4 - g, h, i5 - j, k, l`

now our answer will be of 3 length let it be Q = _ _ _

Now the firstcall which goes to printkeypadstring function is:

`printKeypadString( "345", "", 0, 0 )`

in line 17 digit = 3 as "345"[0] = "3" and "3" - "0" = 3 ;

after that control passes to loop. The loop places all the chars associated with digit=3 at 0th position of Q i.e.
at Q = _ _ _
the chars associated with 3 are d,e,f. It puts d first. Q now becomes Q = d _ _.
Then it calls

`printKeypadString( "345", "d", 1, 1 )`

It generates the value of digit which is 4. chars associated with 4 are g,h,i. It put first one i.e. g at Q[1] so Q = d g _.

Now again the printKeypadString function is called as:

`printKeypadString( "345", "dg", 2, 2 )`

It generates the value of digit which is 5, the first char associated with 5 is j, it puts j at Q[2] i.e. Q = dgj.

Now again the printKeypadString function is called as:

`printKeypadString( "345", "dgj", 3, 3 )`

Now since "345" has only 3 chars therefore it's [3] i.e. "345"[3] = '%uFFFD'.
SO THE CONTROL PASSES BACK TO THE LOOP FROM WHERE IT WAS CALLED THAT IS THAT STEP WHEN Q BECAME Q = dgj

Now k is incremented and value of Q = dgj changes to dgk. Then dgl. After this when keypad[5][3] is called which is '%uFFFD' so control passes to state when Q became Q = dg_.

Now k gets incremented and Q becomes Q = dh_. Same process repeats. Now

`dhjdhkdhl`

will be generated then

`dijdikdil.........egjegkegl`
And same process goes on until all possible letter combinations generate.

# SUBMIT HERE

#### More Articles of Shubh Bansal:

Name Views Likes
Leetcode 1217. Minimum Cost to Move Chips to The Same Position 601 2
Combinations of letters from a number on given phone keypad. 1933 0