Letter Combinations of a Phone Number

DFS

    int cnt[10] = {0,0,3,3,3,3,3,4,3,4};
    char map[10][5] = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
    vector<string> letterCombinations(string digits) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int n = digits.size();
        vector<string> result;
        string path;
        
        combination(0,n,digits,path,result);
        return result;
    }
    
    void combination(int pos,int n,string& digits,string path,vector<string>& result)
    {
        if(pos == n)
        {
            result.push_back(path);
            return;
        }
        int num = digits[pos]-'0';
        if(cnt[num]>0)
        {
            for(int i=0;i<cnt[num];i++)
                combination(pos+1,n,digits,path+map[num][i],result);  
        }else
            combination(pos+1,n,digits,path,result);
        
    }

  

posted @ 2013-08-11 17:32  summer_zhou  阅读(168)  评论(0编辑  收藏  举报