我正在练习在哥兰和锈的leedcode写作解决方案。我为这个问题写了一个解决方案,https://leetcode.com/problems/letter-combinations-of-a-phone-number/ 在戈兰和生锈
package main
func letterCombinations(digits string) []string {
if len(digits) == 0 {
return []string{}
}
letters := [][]string{
{},
{},
{"a", "b", "c"},
{"d", "e", "f"},
{"g", "h", "i"},
{"j", "k", "l"},
{"m", "n", "o"},
{"p", "q", "r", "s"},
{"t", "u", "v"},
{"w", "x", "y", "z"},
}
var gen func(index int, digits string) []string
gen = func(index int, digits string) []string {
result := make([]string, 0)
row := letters[int(digits[index]-'0')]
index++
for _, letter := range row {
if index < len(digits) {
for _, res := range gen(index, digits) {
result = append(result, letter+res)
}
} else {
result = append(result, letter)
}
}
return result
}
return gen(0, digits)
}
func main() {
for i := 0; i < 10000; i++ {
letterCombinations("23456789")
}
}
这生锈了
struct Solution;
impl Solution {
pub fn letter_combinations(digits: String) -> Vec<String> {
if digits.len() == 0 {
return vec![];
}
let letters: [[char; 5]; 10] = [
[0 as char, '0', '0', '0', '0'],
[0 as char, '0', '0', '0', '0'],
[3 as char, 'a', 'b', 'c', '0'], // 2
[3 as char, 'd', 'e', 'f', '0'], // 3
[3 as char, 'g', 'h', 'i', '0'], // 4
[3 as char, 'j', 'k', 'l', '0'], // 5
[3 as char, 'm', 'n', 'o', '0'], // 6
[4 as char, 'p', 'q', 'r', 's'], // 7
[3 as char, 't', 'u', 'v', '0'], // 8
[4 as char, 'w', 'x', 'y', 'z'], // 9
];
我通过10 000次迭代运行每个解决方案。Golang解决方案在我的笔记本电脑上需要60秒。生锈溶液需要556秒,大约慢10倍。我猜这是因为golang垃圾回收器不会在程序期间将堆内存返回给操作系统,而是在每次迭代中使用预先分配的内存。但是,每次调用函数字母组合()都会从操作系统中分配内存并将其释放回去。所以生锈速度较慢。我说的对吗?
婷婷同学_
相关分类