从电话号码数字打印所有可能的单词

时间:2016-10-17 07:21:24

标签: algorithm

我的问题是七位数可能有多少个单词,每个数字代表n个字母?当我们在键入文本时按2,3,4可能形成的单词是(按字母顺序排列):

如果输入数字是234, adg adh adi aeg aeh aei afg afh afi bdg bdh bdi beg beh bei bfg bfh bfi cdg cdh cdi ceg ceh cei cfg cfh cfi

2 个答案:

答案 0 :(得分:2)

递归解决方案:

void printAllWordsFromPhoneNumber(string phonenumber)
{
    printAllWordsFromPrefixAndPhoneNumber("", phonenumber);
}

string getLettersForNumber(char digit)
{
    string [] table = {"", "", "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ"};
    bool valid = ((digit >= '0') && (digit <= '9'));
    return valid ? table[digit-'0'] : "";
}

void printAllWordsFromPrefixAndPhoneNumber(string prefix, string remaining)
{
   if ( (remaining == null) || (remaining.length()==0) )
   {
       System.out.println(prefix);
   }
   else
   {
       string chars_in_digit = getLettersForNumber(remaining.charAt(0));

       for (int i = 0; i < chars_in_digit.length(); i++)
       {
           string newprefix = prefix + chars_in_digit.charAt(i);
           string newremaining = remaining.substr(1);
           printAllWordsFromPrefixAndPhoneNumber(newprefix, newremaining);
       }

       // special case for "0" and "1" since neither has any letters associated with them.
       if (chars_in_digit.length() == 0)
       {
           printAllWordsFromPrefixAndPhoneNumber(prefix, remaining.substr(1));
       }

   }
}

答案 1 :(得分:-1)

//调用此

   List<String> perms = permutation("", "abc");
   // instead of "abc write your 7 digit number

            String[] array = new String[perms.size()];
            for (int i = 0; i < perms.size(); i++) {
                array[i] = perms.get(i);
            }

            int x = array.length;

            for (final String anArray : array) {
                System.out.println(anArray);
            }

//方法

private static List<String> permutation(String prefix, String str) {
        List<String> permutations = new ArrayList<>();
        int n = str.length();
        if (n == 0) {
            permutations.add(prefix);
        } else {
            for (int i = 0; i < n; i++) {
                permutations.addAll(permutation(prefix + str.charAt(i), str.substring(i + 1, n) + str.substring(0, i)));
            }
        }
        return permutations;
    }