How to get all the combinations of the keypad value in a mobile by backtracking using C#?


The problem can be broken down into smaller and simple "subproblems", which can be further divided into yet simpler and smaller subproblems. We take each and every digit one by one and count all ndigits reachable from any digit, use a map to store the mapping of digits reachable from every digit. When the digit becomes n-digit, update the count.

Example

 Live Demo

using System;
using System.Collections.Generic;
namespace ConsoleApplication{
   public class BackTracking{
      private string GetKeyPadValueBasedOnInput(string digit){
         Dictionary keypad = new Dictionary();
         keypad.Add("2", "abc");
         keypad.Add("3", "def");
         keypad.Add("4", "ghi");
         keypad.Add("5", "jkl");
         keypad.Add("6", "mno");
         keypad.Add("7", "pqrs");
         keypad.Add("8", "tuv");
         keypad.Add("9", "wxyz");
         return keypad.GetValueOrDefault(digit);
      }
      public void FindSequence(string currentList, string digits, List output){
         if (digits.Length == 0){
            output.Add(currentList);
            return;
         }
         else{
            string digit = digits.Substring(0, 1);
            string letters = GetKeyPadValueBasedOnInput(digit);
            for (int i = 0; i < letters.Length; i++){
               char letter = GetCHarFromString(letters, i);
               FindSequence(currentList + letter, digits.Substring(1), output);
            }
         }
      }
      private char GetCHarFromString(string letters, int value){
         char[] charArr = letters.ToCharArray();
         return charArr[value];
      }
   }
   class Program{
      static void Main(string[] args){
         BackTracking b = new BackTracking();
         List<string> output = new List<string>();
         b.FindSequence("", "34", output);
         foreach (var item in output){
            Console.WriteLine(item);
         }
      }
   }
}

Output

dg
dh
di
eg
eh
ei
fg
fh
fi

Updated on: 27-Aug-2021

197 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements