Here is LeetCode question 17:
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.
(https://leetcode.com/problems/letter-combinations-of-a-phone-number/)
Below is my DFS recursive code:
class Solution {
public static final String[] map = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
public List<String> letterCombinations(String digits){
List<String> result = new ArrayList<String>();
if(digits == null || digits.length() == 0){return result;}
int curr_index = 0;
StringBuilder prefix = new StringBuilder("");
update_result(digits, prefix, curr_index, result);
return result;
}
private void update_result(String digits, StringBuilder prefix, int curr_index, List<String> result){
if(curr_index >= digits.length()){
result.add(prefix.toString());
return;
}
else{
String letters = map[ digits.charAt(curr_index) - '0' ];
for(int i = 0; i < letters.length(); i++){
prefix.append( letters.charAt(i) );
update_result(digits, prefix, curr_index+1, result);
prefix.deleteCharAt(prefix.length() -1);
}
return;
}
}
}
In the LeetCode solutions, it says the time complexity is O(n*n^4), where n is the length of the input. I have trouble understanding except the n^4, where the remaining extra n comes from.
My analysis of my code is: T(n) = O(1) + 4T(n-1). (The for loop is repeated for 4 times which length decremented by 1. And in the loop constant time is required for update the prefix String.)
It solves to 1 + 4 + 4^1+ ... + 4^n = O(4^n)
Can anyone help with why the solution says the time complexity is O(n*4^n)?