Two approaches using golang


  • 0
    S

    I stored the number-letter map like this:

    var numberMap = map[byte][]string{
    	'2': []string{"a", "b", "c"},
    	'3': []string{"d", "e", "f"},
    	'4': []string{"g", "h", "i"},
    	'5': []string{"j", "k", "l"},
    	'6': []string{"m", "n", "o"},
    	'7': []string{"p", "q", "r", "s"},
    	'8': []string{"t", "u", "v"},
    	'9': []string{"w", "x", "y", "z"},
    }
    

    Here is a "depth-first" approach:

    func depthSolution(s string) []string {
    	if len(s) == 1 {
    		return numberMap[s[0]]
    	}
    	returnArr := []string{}
    	for _, e := range numberMap[s[0]] {
    		for _, e1 := range depthSolution(s[1:]) {
    			returnArr = append(returnArr, e+e1)
    		}
    	}
    	return returnArr
    }
    

    Here is a "breadth-first" approach:

    func breadthSolution(s string) []string {
    	returnQueue := numberMap[(s[0])]
    	position := 1
    	for position < len(s) {
    		newQueue := []string{}
    		for _, e := range returnQueue {
    			for _, e1 := range numberMap[s[position]] {
    				newQueue = append(newQueue, e+e1)
    			}
    		}
    		returnQueue = newQueue
    		position++
    	}
    	return returnQueue
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.