【问题标题】:Time/space complexity of this algorithm to find letter combinations of a phone number?这个算法的时间/空间复杂度来查找电话号码的字母组合?
【发布时间】:2017-12-16 05:56:32
【问题描述】:

我不确定它的时间/空间复杂度,因为虽然它有一个双 for 循环 O(n^2),但在一个 for 循环内 O(n),所以 O(n^3),它也有接受一个数字并生成字母排列,有点像 O(n number of digits xm! permutations for the letters)。

/**
 * @param {string} digits
 * @return {string[]}
 */

var permutate = function(currentCombinations, nextLetters) {
    var results = [];

    for (var i = 0; i < currentCombinations.length; i++) {
       for (var j = 0; j < nextLetters.length; j++) {
           results.push(currentCombinations[i] + nextLetters[j]);
       }
    }

    console.log(currentCombinations, '+', nextLetters, '=>', results);

    return results;
}

var letterCombinations = function(digits) {
    if (digits === "") return [];

    var phoneMap = ["0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"];

    var result = [""];

    for (var i = 0; i < digits.length; i++) {
        var letterMappingsForDigit = phoneMap[digits[i]];
        result = permutate(result, letterMappingsForDigit);
    }

    return result;
};

letterCombinations("23");
// => [ 'ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf' ]

【问题讨论】:

  • 一个数字可以使用两次吗?例如:字母组合(“111122223331123”)

标签: algorithm time-complexity space-complexity


【解决方案1】:

假设您不会对同一 i 使用两次 phoneMap[i],即最终调用是 letterCombinations("0123....len(phoneMap)-1"),

那我认为是,其中a[x]是phoneMap[x]

的长度

考虑letterCombinations("012")的调用,分别让phoneMap[1], phoneMap[2], phoneMap[3] be 3,5,2的长度。

然后您的算法将执行O(1) 推送1*3 + 1*3*5 + 1*3*5*2 次,即

a[0] + a[0]a[1] + a[0]a[1]a[2] 其中a = [len(phoneMap[0]), len(phoneMap[1]), len(phoneMap[2])]


如果可以接受不那么紧的界限,我假设你可以重用phoneMap[i],那么上面的复杂性可以简化为,其中L是phoneMap中最长的字符串,并且n 是您传递给letterCombinations 的数字长度。

因为上面的公式会变成简单的几何和,比如说L = 5,你调用letterCombinations("5555"),那么和就是5 + 5*5 + 5*5*5 + 5*5*5*5 = 5*(5^(n) - 1)/(5-1) = O(5^n)

【讨论】:

    猜你喜欢
    • 2021-08-07
    • 1970-01-01
    • 1970-01-01
    • 2020-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-08
    相关资源
    最近更新 更多