/*
Given a hashmap M which is a mapping of characters to arrays of substitute characters, and an input string S, return an array of all possible mutations of S (where any character in S can be substituted with one of its substitutes in M, if it exists).
What is the time complexity? What is the space complexity? Can you optimize either?
Example input:
M = { f: [F, 4], b: [B, 8] }
S = fab
Expected output:
[fab, Fab, 4ab, faB, FaB, 4aB, fa8, Fa8, 4a8]
*/
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>
#include <string>
#include <unordered_map>
#include <iostream>
using namespace std;
void permuteHelp(unordered_map<char,vector<char>> &mmap, string &s, int level, string &seq, vector<string> &res){
if(level == s.size()){
res.push_back(seq);
return;
}
char c= s[level];
if(mmap.count(c)){
seq.append(1,c); //add itself.
permuteHelp(mmap,s,level+1,seq,res);
seq.resize(seq.size()-1);
for(int i=0;i<mmap[c].size();++i){
seq.append(1,mmap[c][i]);
permuteHelp(mmap,s,level+1,seq,res);
seq.resize(seq.size()-1); //backtrack!!!
}
}
else{
seq.append(1,c);
permuteHelp(mmap,s,level+1,seq,res);
seq.resize(seq.size()-1);
}
return;
}
vector<string> lettercombi(unordered_map<char,vector<char>> &mmap, string s){
vector<string> res;
string seq;
permuteHelp(mmap, s, 0, seq, res);
return res;
}
int main(){
unordered_map<char,vector<char>> mmap;
vector<string> res;
char a[] = {'F','4'};
vector<char> veca(a,a+2);
mmap.insert(make_pair('f',veca));
char b[] = {'B','8'};
vector<char> vecb(b,b+2);
mmap.insert(make_pair('b',vecb));
res = lettercombi(mmap,"fab");
for(int i=0;i<res.size();++i){
cout<< res[i]<<endl;
}
getchar();
return 0;
}
No comments:
Post a Comment