码迷,mamicode.com
首页 > 其他好文 > 详细

3.2 电话号码对应英语单词

时间:2015-04-21 11:19:16      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:

 原始问题如下:手机上面的数字键均对应了几个字符,譬如2对应了a,b,c。问题是当输入一段数字后,求出所有可能的字符组合


第一种方法:假设电话号码是n个数字,那么就n个for循环。

这方法果断不好


第二个方法:

#include <iostream>
#include <string>

using namespace std;

char c[10][10] =
{
    "",
    "",
    "ABC",
    "DEF",
    "GHI",
    "JKL",
    "MNO",
    "PQRS",
    "TUV",
    "WXYZ",
};

int total[10] = {0, 0, 3, 3, 3, 3, 3, 4, 3, 4};
int tel_length;
int number[10], answer[10];

int main(int argc, const char * argv[]) {
    cin >> tel_length;
    for(int i = 0; i < tel_length; ++i) cin >> number[i];
    memset(answer, 0, sizeof(answer));
    while(true) {
        for (int i = 0; i < tel_length; i++) {
            printf("%c", c[number[i]][answer[i]]);
        }
        puts("\n");
        int k = tel_length-1;
        while(k >= 0) {
            if(answer[k] < total[number[k]] - 1) {
                answer[k]++;
                break;
            } else {
                answer[k] = 0;
                k--;
            }
        }
        if(k < 0) break;
    }
    return 0;
}


第三个方法:回溯法:


#include <iostream>
#include <string>

using namespace std;

char c[10][10] =
{
    "",
    "",
    "ABC",
    "DEF",
    "GHI",
    "JKL",
    "MNO",
    "PQRS",
    "TUV",
    "WXYZ",
};

int total[10] = {0, 0, 3, 3, 3, 3, 3, 4, 3, 4};
int tel_length;
int number[10], answer[10];

void RecursiveSearch(int *number, int *answer, int index, int n) {
    if(index == n) {
        for(int i = 0; i < n; ++i) cout << c[number[i]][answer[i]];
        cout << endl;
        return ;
    } else {
        for (answer[index] = 0; answer[index] < total[number[index]]; answer[index]++) {
            RecursiveSearch(number, answer, index+1, n);
        }
    }
}

int main(int argc, const char * argv[]) {
    cin >> tel_length;
    for(int i = 0; i < tel_length; ++i) cin >> number[i];
    memset(answer, sizeof(answer), 0);
    RecursiveSearch(number, answer, 0, tel_length);
    return 0;
}


3.2 电话号码对应英语单词

标签:

原文地址:http://blog.csdn.net/u010470972/article/details/45166613

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!