Letter Combinations of a Phone Number

题目:Given a digit string, 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.

        

Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

思路:深搜+动态规划

思路就是,设置一个限制条件,满足位数,就存入,这是通用的,start代表digits里面的索引值。另外本程序并不需要判断是否start越界的,也能够通过,不过最好是判断下,现在还不能够说清楚为什么。

代码:

class Solution {
public:
//https://leetcode.com/problems/letter-combinations-of-a-phone-number/
    vector<string> letterCombinations(string digits) {
        string table[]={"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};//  (number:2-9)==(0-7)
        vector<string> result;
        if(digits.empty()){     //考虑输入为空的情况
            return result;   
        }
        string s;//缓存
        combinationHelper(table,digits,0,s,result);//table[]不对
        return result;
    }
    
    void combinationHelper(string table[],string &digits,int start,string &s,vector<string> &result){
        if(start==digits.size()){
            result.push_back(s);
            return;
        }//限制条件
        
        int i=digits[start]-'2';
        if(i<0||i>7){
            return;//本来以为这句是没啥用的,只是后面start不断+1,会导致溢出,所以有用。
        }
        
        for(int j=0;j<table[i].size();j++){
            s.push_back(table[i][j]);
            combinationHelper(table,digits,start+1,s,result);
            s.pop_back();
        }
    }
};


posted @ 2015-10-08 20:35  JSRGFJZ6  阅读(125)  评论(0编辑  收藏  举报