📜  电话号码的迭代字母组合

📅  最后修改于: 2021-05-31 17:15:23             🧑  作者: Mango

给定一个包含[0,9]中数字的整数数组,任务是打印数字可能代表的所有可能的字母组合。
遵循数字到字母的映射(就像在电话按钮上一样)。请注意01不会映射到任何字母。下图显示了所有映射:

例子:

方法:现在让我们考虑一下如何以迭代方式解决该问题。递归解决方案是直观且通用的。我们继续递归地添加每个可能的字母,这将生成所有可能的字符串。
让我们考虑一下如何使用递归解决方案构建迭代解决方案。通过使用堆栈可以进行递归。因此,如果我们使用堆栈而不是递归函数,那将是一个迭代解决方案吗?从技术上讲,可以这样说,但是我们在逻辑上并没有做任何不同的事情。
堆栈是LIFO DS。我们可以使用其他数据结构吗?如果我们使用FIFO DS,会有什么区别?假设有一个队列。由于BFS是按队列完成的,而DFS是按堆栈完成的,两者之间有什么区别吗?
DFS和BFS之间的区别与此问题类似。在DFS中,我们将一一找到树中的每条路径。它将首先执行路径的所有步骤,而BFS一次将所有路径构建在一起。
因此,队列将完美地解决此问题。两种使用队列和堆栈的算法之间的唯一区别将是它们的形成方式。堆栈将完全一一形成所有字符串,而队列将一起形成所有字符串,即经过x次传递之后,所有字符串的长度将为x。

例如:

If the given number is "23", 
then using queue, the letter combinations 
obtained will be:
["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"] 
and using stack, the letter combinations obtained will 
be:
["cf","ce","cd","bf","be","bd","af","ae","ad"].

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Function to return a vector that contains
// all the generated letter combinations
vector letterCombinationsUtil(const int number[],
                                      int n,
                                      const string table[])
{
    // To store the generated letter combinations
    vector list;
 
    queue q;
    q.push("");
 
    while (!q.empty()) {
        string s = q.front();
        q.pop();
 
        // If complete word is generated
        // push it in the list
        if (s.length() == n)
            list.push_back(s);
        else
 
            // Try all possible letters for current digit
            // in number[]
            for (auto letter : table[number[s.length()]])
                q.push(s + letter);
    }
 
    // Return the generated list
    return list;
}
 
// Function that creates the mapping and
// calls letterCombinationsUtil
void letterCombinations(const int number[], int n)
{
 
    // table[i] stores all characters that
    // corresponds to ith digit in phone
    string table[10]
        = { "0",   "1",   "abc",  "def", "ghi",
            "jkl", "mno", "pqrs", "tuv", "wxyz" };
 
    vector list
        = letterCombinationsUtil(number, n, table);
 
    // Print the contents of the vector
    for (auto word : list)
        cout << word << " ";
 
    return;
}
 
// Driver code
int main()
{
    int number[] = { 2, 3 };
    int n = sizeof(number) / sizeof(number[0]);
 
    // Function call
    letterCombinations(number, n);
 
    return 0;
}


Java
// Java implementation of the approach
import java.io.*;
import java.util.*;
 
class GFG {
    // Function to return a vector that contains
    // all the generated letter combinations
    static ArrayList
    letterCombinationsUtil(int[] number, int n,
                           String[] table)
    {
        // To store the generated letter combinations
        ArrayList list = new ArrayList<>();
 
        Queue q = new LinkedList<>();
        q.add("");
 
        while (!q.isEmpty()) {
            String s = q.remove();
 
            // If complete word is generated
            // push it in the list
            if (s.length() == n)
                list.add(s);
            else {
                String val = table[number[s.length()]];
                for (int i = 0; i < val.length(); i++)
                {
                    q.add(s + val.charAt(i));
                }
            }
        }
        return list;
    }
 
    // Function that creates the mapping and
    // calls letterCombinationsUtil
    static void letterCombinations(int[] number, int n)
    {
        // table[i] stores all characters that
        // corresponds to ith digit in phone
        String[] table
            = { "0",   "1",   "abc",  "def", "ghi",
                "jkl", "mno", "pqrs", "tuv", "wxyz" };
 
        ArrayList list
            = letterCombinationsUtil(number, n, table);
 
        // Print the contents of the list
        for (int i = 0; i < list.size(); i++) {
            System.out.print(list.get(i) + " ");
        }
    }
 
    // Driver code
    public static void main(String args[])
    {
        int[] number = { 2, 3 };
        int n = number.length;
       
        // Funciton call
        letterCombinations(number, n);
    }
}
 
// This code is contributed by rachana soma


Python
# Python3 implementation of the approach
from collections import deque
 
# Function to return a list that contains
# all the generated letter combinations
 
 
def letterCombinationsUtil(number, n, table):
 
    list = []
    q = deque()
    q.append("")
 
    while len(q) != 0:
        s = q.pop()
 
        # If complete word is generated
        # push it in the list
        if len(s) == n:
            list.append(s)
        else:
 
            # Try all possible letters for current digit
            # in number[]
            for letter in table[number[len(s)]]:
                q.append(s + letter)
 
    # Return the generated list
    return list
 
 
# Function that creates the mapping and
# calls letterCombinationsUtil
def letterCombinations(number, n):
 
    # table[i] stores all characters that
    # corresponds to ith digit in phone
    table = ["0", "1", "abc", "def", "ghi", "jkl",
             "mno", "pqrs", "tuv", "wxyz"]
 
    list = letterCombinationsUtil(number, n, table)
 
    s = ""
    for word in list:
        s += word + " "
 
    print(s)
    return
 
 
# Driver code
number = [2, 3]
n = len(number)
 
# Function call
letterCombinations(number, n)


C#
// C# implementation of the approach
using System;
using System.Collections.Generic;
 
class GFG {
    // Function to return a vector that contains
    // all the generated letter combinations
    static List
    letterCombinationsUtil(int[] number, int n,
                           String[] table)
    {
        // To store the generated letter combinations
        List list = new List();
 
        Queue q = new Queue();
        q.Enqueue("");
 
        while (q.Count != 0) {
            String s = q.Dequeue();
 
            // If complete word is generated
            // push it in the list
            if (s.Length == n)
                list.Add(s);
            else {
                String val = table[number[s.Length]];
                for (int i = 0; i < val.Length; i++) {
                    q.Enqueue(s + val[i]);
                }
            }
        }
        return list;
    }
 
    // Function that creates the mapping and
    // calls letterCombinationsUtil
    static void letterCombinations(int[] number, int n)
    {
        // table[i] stores all characters that
        // corresponds to ith digit in phone
        String[] table
            = { "0",   "1",   "abc",  "def", "ghi",
                "jkl", "mno", "pqrs", "tuv", "wxyz" };
 
        List list
            = letterCombinationsUtil(number, n, table);
 
        // Print the contents of the list
        for (int i = 0; i < list.Count; i++) {
            Console.Write(list[i] + " ");
        }
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        int[] number = { 2, 3 };
        int n = number.Length;
       
        // Function call
        letterCombinations(number, n);
    }
}
 
// This code is contributed by Princi Singh


输出
ad ae af bd be bf cd ce cf 

如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。