Find all strings formed from characters mapped to digits of a number | C ++ program to find all strings formed from a given number where each digit maps to given characters . ; Function to find all strings formed from a given number where each digit maps to given characters . ; vector of strings to store output ; stores index of first occurrence of the digits in input ; maintains index of current digit considered ; for each digit ; store index of first occurrence of the digit in the map ; clear vector contents for future use ; do for each character thats maps to the digit ; for first digit , simply push all its mapped characters in the output list ; from second digit onwards ; for each string in output list append current character to it . ; convert current character to string ; Imp - If this is not the first occurrence of the digit , use same character as used in its first occurrence ; store strings formed by current digit ; nothing more needed to be done if this is not the first occurrence of the digit ; replace contents of output list with temp list ; Driver program ; vector to store the mappings ; vector to store input number ; print all possible strings
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < string > findCombinations ( vector < int > input , vector < char > table [ ] ) { vector < string > out , temp ; unordered_map < int , int > mp ; int index = 0 ; for ( int d : input ) { if ( mp . find ( d ) == mp . end ( ) ) mp [ d ] = index ; temp . clear ( ) ; for ( int i = 0 ; i < table [ d - 1 ] . size ( ) ; i ++ ) { if ( index == 0 ) { string s ( 1 , table [ d - 1 ] . at ( i ) ) ; out . push_back ( s ) ; } if ( index > 0 ) { for ( string str : out ) { string s ( 1 , table [ d - 1 ] . at ( i ) ) ; if ( mp [ d ] != index ) s = str [ mp [ d ] ] ; str = str + s ; temp . push_back ( str ) ; } if ( mp [ d ] != index ) break ; } } if ( index > 0 ) out = temp ; index ++ ; } return out ; } int main ( ) { vector < char > table [ ] = { { ' A ' , ' B ' , ' C ' } , { ' D ' , ' E ' , ' F ' } , { ' G ' , ' H ' , ' I ' } , { ' J ' , ' K ' , ' L ' } , { ' M ' , ' N ' , ' O ' } , { ' P ' , ' Q ' , ' R ' } , { ' S ' , ' T ' , ' U ' } , { ' V ' , ' W ' , ' X ' } , { ' Y ' , ' Z ' } } ; vector < int > input = { 1 , 2 , 1 } ; vector < string > out = findCombinations ( input , table ) ; for ( string it : out ) cout << it << " ▁ " ; return 0 ; }