How does Backtracking actually work in Elixir? I’m currently working on this leetcode problem where we have been given a string of digits and we have to find all possible letter combinations that the number can represent. However, I can’t seem to understand how backtracking will work here due to immutability of Elixir.
I tried writing my solution based on this C++ code (Solution - II) given below:
defmodule Solution do
def letter_combinations(digits) do
ans = []
mappings = %{
"2" => "abc",
"3" => "def",
"4" => "ghi",
"5" => "jkl",
"6" => "mno",
"7" => "pqrs",
"8" => "tuv",
"9" => "wxyz"
}
cond do
String.equivalent?(digits, "") -> ans
true ->
combination = ""
helper(digits, mappings, ans, 0, combination) |> :lists.reverse
end
end
def helper(digits, mappings, ans, i, combi) do
cond do
i == String.length(digits) -> [combi | ans]
true ->
list = mappings[String.at(digits, i)] |> String.graphemes
list |> Enum.reduce({ans, combi}, fn(c, {ans, combi}) ->
combi = combi <> c
ans = helper(digits, mappings, ans, i+1, combi)
combi = String.slice(combi, 0..String.length(combi)-1) # Backtracking
{ans, combi}
end)
|> elem(0)
end
end
end
digits ="23"
IO.inspect Solution.letter_combinations(digits)
What I’m doing here is creating mappings
that maps the phone digits with the corresponding alphabets. Then, inside the helper
function, I check to see if the variable i
is equal to the size of the string (in this case, we will return ans
since our condition has been met).
Then, I extract the graphemes from the map using the digits string as the key and then apply reduce over it. Inside the reduce, I concatenate the letter combinations and then update my ans
list along with the backtracking process.
However, my results don’t seem to be accurate and I seem to be getting the output ["ad", "ade", "adef", "abd", "abde", "abdef", "abcd", "abcde", "abcdef"]
when it should be ["ad","ae","af","bd","be","bf","cd","ce","cf"]
.
Can someone guide me as to what am I doing wrong here? Also, for general purposes, how can we perform backtracking in Elixir if it is possible?
Any help will be appreciated. Thank you!