我的問題是,有多少個單詞可能用七個數字代替,每個數字代表n個字母?當我們按下2,3,4-打字時可形成一個文本可能的話是(按字母順序):打印從電話號碼的數字所有可能的單詞
如果輸入數目是234, ADG ADH ADI AEG AEH AEI AFG AFH AFI BDG BDH BDI BEG BEH貝BFG BFH BFI CDG CDH CDI CEG CEH CEI CFG CFH CFI
我的問題是,有多少個單詞可能用七個數字代替,每個數字代表n個字母?當我們按下2,3,4-打字時可形成一個文本可能的話是(按字母順序):打印從電話號碼的數字所有可能的單詞
如果輸入數目是234, ADG ADH ADI AEG AEH AEI AFG AFH AFI BDG BDH BDI BEG BEH貝BFG BFH BFI CDG CDH CDI CEG CEH CEI CFG CFH CFI
//調用此
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;
}
遞歸溶液:
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));
}
}
}
請做upvote這個問題 –
你說的是舊手機,手機上的每個數字都有3個字母? – mjosh
是的,我正在考慮舊手機。 –
@SuryaPrakashKushawah我希望它能幫助檢查[this](http://www.geeksforgeeks.org/find-possible-words-phone-digits/)。 – Raghavendra