17. Letter Combinations of a Phone Number [M] phone number letter combination

topic

Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.
A mapping of digit to letters ( just like on the telephone buttons ) is given below. Note that 1 does not map to any letters.

Thinking

A thought: recursion

First, establish correspondence between numbers and letters on the phone button, it is easy to think of the use of C ++ in map

Thinking two: backtracking

Tips

Recursion

Backtracking

C++

  • A thought
    map<int,string> table={{2,"abc"},{3,"def"},{4,"ghi"},{5,"jkl"},{6,"mno"},{7,"pqrs"},{8,"tuv"},{9,"wxyz"}};
    
    vector<string> letterCombinations(string digits) {
        
        vector<string> result;
        
        if(digits.length()==0)
            return result;
            
        
        combineNum(result,0,"",digits);
        
        return result;
    }
    
    void combineNum(vector<string>& r,int count,const string& a,const string& b){
    
        if (count == b.size()){
          r.push_back(a);
          return;
        }

        string curStr = table[b[count] - '0'];
    
        for (char s : curStr){ 
            combineNum(r, count + 1, a + s, b);
        }   
    }
  • Ideas two

python

Guess you like

Origin www.cnblogs.com/Jessey-Ge/p/10993495.html