StringBuildersb=newStringBuilder(); for (inti=0; i < len; i++) { sb.append("a"); }
for (inti=0; i < letters[digitsArr[0] - 2].length(); i++) { sb.replace(0, 1, letters[digitsArr[0] - 2].charAt(i) + ""); if (len == 1) { ans.add(sb.substring(0, 1)); }
for (intj=0; len >= 2 && j < letters[digitsArr[1] - 2].length(); j++) { sb.replace(1, 2, letters[digitsArr[1] - 2].charAt(j) + ""); if (len == 2) { ans.add(sb.toString()); }
for (intk=0; len >= 3 && k < letters[digitsArr[2] - 2].length(); k++) { sb.replace(2, 3, letters[digitsArr[2] - 2].charAt(k) + ""); if (len == 3) { ans.add(sb.toString()); }
for (intl=0; len >= 4 && l < letters[digitsArr[3] - 2].length(); l++) { sb.replace(3, 4, letters[digitsArr[3] - 2].charAt(l) + ""); ans.add(sb.toString()); } } } }
return ans; }
Analysis
Time Complexity: \(O(4^N)\)
Space Complexity: \(O(N)\)
Backtracking
For the first number, there are \(3\) options, and \(3\) options for the second number and so on.
The combinations from the first to the last will expand into a recursive tree.
When the index reaches the end of digits, we get a combination, and add it to the result, end the current recursion. Finally we will get all the combinations.
for (inti=0; i < len - 2; i++) { for (intj= i + 1; j < len - 1; j++) { for (intk= j + 1; k < len; k++) { if (nums[i] < nums[k] && nums[k] < nums[j]) { returntrue; } } } }
returnfalse; }
Analysis
Time Complexity: \(O(n^3)\).
Space Complexity: \(O(1)\).
BF O(n^2)
Noticed that \(\textit{nums}[j]\) is the peak of the \(3\) elements, suppose the current element is \(\textit{nums}[j]\), we have to find the element \(\textit{nums}[k]\) that is smaller than \(\textit{nums}[j]\) after \(j\), and the element \(\textit{nums}[i]\) that is smaller than \(\textit{nums}[k]\) before \(j\).
Scan left from \(j\) to \(0\), \(0 \le i \lt j\), whether there is \(\textit{nums}[i] < \textit{nums}[j]\), update the mininum \(\textit{leftMin}\);
Scan right from \(j\) to the end, \(j + 1 \le k \lt len\), whether there is \(\textit{nums}[k] < \textit{nums}[j]\), update the maxinum \(\textit{rightMax}\);
If exists and \(\textit{leftMin} < \textit{rightMax}\) , return true.