[Algorithm brush question] Non-recursive solution to the letter combination of phone numbers

Problem: 17. Letter combination of phone number

train of thought

This question feels the feeling of DFS and BFS. It seems that it should be done with the idea of ​​​​a graph, but here is still a trick. A relatively simple method is used to replace the recursion of DFS and BFS, and an iterative method is used. solve problems.

problem solving method

First of all, it is necessary to decompose the sub-problem for this problem. For example, if the user enters a 2, then the solution must be ['a', 'b', 'c']. If the user enters a 3 on the basis of 2, then The result we appear must be the result of adding 3 on the basis of 2.
Therefore, if the result of 3 appears, then we need to expand the original array. For example, the result of 3 is ['d', 'e', ​​'f']
, then our final result must be 3x3 = 9, therefore, we can directly expand the array to len(di_ch[key]) length, and pass The sorted method sorts. After sorting, since the lexicographical order is ordered, string addition can be performed directly, and the original array can be directly modified through the key.
The final time complexity is O(n^2), and the overall effect is still very good.

the complexity

  • time complexity:

Add time complexity, example: O ( n 2 ) O(n^2)O ( n2)

  • Space complexity:

Add space complexity, example: O ( n ) O(n)O ( n )

Code


class Solution:
    di_ch ={
        '2':'abc',
        '3':'def',
        '4':'ghi',
        '5':'jkl',
        '6':'mno',
        '7':'pqrs',
        '8':'tuv',
        '9':'wxyz'
    }

    def solve(self,res,info):
        di_ch = self.di_ch
        if len(res) != 0:
            ori_len = len(res)
            res = res * len(di_ch[info])
            res = sorted(res)

            for index in range(0,len(res)):
                key = index % len(di_ch[info])
                res[index] = res[index] + di_ch[info][key]
        else:
            for item in di_ch[info]:
                res.append(item)
        return res

    def letterCombinations(self, digits: str) -> List[str]:
        res = []
        for item in digits:
	        res = self.solve(res,item)
        return res








        
        

Guess you like

Origin blog.csdn.net/qq_27180763/article/details/129478527