【DFS】LeetCode 17. Alphabet combinations of phone numbers

insert image description here

Halo, this is Ppeua. Usually, I mainly update C language, C++, data structure algorithm... Follow me bua if you are interested!
img

Table of contents

topic:

insert image description here

Example:

insert image description here

answer:

This is a full-arrangement problem, let's take a look at the example first.

Look at the first example: input "23", which corresponds to "abc" and "de". According to the characteristics of the full arrangement, we first write them in a layered structure, and then arrange and combine them sequentially

Specifically:

First select one of the zeroth layer ("abc"), and then select one of the first layer ("de"). At this time, the second layer is reached. At this time, the number of layers is equal to the size() of the input "23", Indicates that the current permutation is over. Then store the answer and return to the previous layer to continue the next permutation.insert image description here

Let's take a look at the specific code implementation:

Code:

#include<iostream>
#include<vector>
using namespace std;
class Solution {
    
    
public:
    string a[10]={
    
    "","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; 
    void conbinStr(string digits,int level,string combine,vector<string>&v)
    {
    
    
        if(level==digits.size())
        {
    
    
            v.push_back(combine);
            return ;
        }
        int num=digits[level]-'0';
        string str=a[num];

        for(int i=0;i<str.size();i++)
        {
    
    
            conbinStr(digits,level+1,combine+str[i],v);
        }
    }
    vector<string> letterCombinations(string digits) {
    
    
        vector<string>ans;
        if(digits.size()==0)
        {
    
    
            return ans;
        }
        conbinStr(digits,0,"",ans);
        return ans;
    }
};
  1. First clarify the overall idea, we need to conduct a deep search, but the parameters of letterCombinations cannot meet our needs, so we need to customize a function. Digits (question string ), Level ( number of layers ), Combine ( combined string ), v ( answer array ), we define a string to correspond to the letter of each button

  2. After that start laminar call
    insert image description here

Guess you like

Origin blog.csdn.net/qq_62839589/article/details/131738720