首页 > 其他 > 详细

LeetCode 17 Letter Combinations of a Phone Number

时间:2015-05-03 20:29:58      阅读:291      评论:0      收藏:0      [点我收藏+]

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.

这个题目很贴近实际应用,树的遍历是个问题,还要下功夫,下面是一个用迭代实现的:

 

class Solution
{
public:
    void init()
    {
        int count = 0;
        for(int i = 1; i<9; ++i)
        {
            string temp;
            for(int j=0; j<3; ++j)
            {
                temp.push_back(a+ count);
                count++;
            }
            if(i==6 || i==8)
            {
                temp.push_back(a+count);
                count++;
            }
            album.push_back(temp);
        }
    }
    void getcombination(string &digits, int i, int n, string str)
    {
        if(i == n)
        {
            ret.push_back(str);
            str.clear();
            return;
        }
        for(int j=0; j != album[digits[i]-2].size(); ++j)
        {
            getcombination(digits, i+1, n, str + album[digits[i] -2][j]);
        }
    }
    vector<string> letterCombinations(string digits)
    {
        if(digits.empty())
        {
            return ret;
        }
        string str;
        init();
        getcombination(digits, 0, digits.size(), str);
        return ret;
    }
    
private:
    vector<string>  album;
    vector<string>  ret;
};

表示这种迭代还是很值得学习,自己的代码能力,哈有结合数据结构分析解决问题的能力还是很不足!!!加油!!!

 

LeetCode 17 Letter Combinations of a Phone Number

原文:http://www.cnblogs.com/bestwangjie/p/4474490.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!