The problem is to find how many complete structures can be formed using the DNA chains. The rule is that the first letter of the new part has to be the same as the last letter of the previous chain.
On the first row you are given an integer: the number of chains. On the next n rows are strings: the chains.
Example:
5
ACGA
ACGA
ACAC
CCCC
CTAC
Output: 4
I tried a recursive backtracking solution, but I am sometimes getting wrong answers. I can't seem to figure out what is wrong.
ans = 0
used = {}
def place(howmanyplaced, allowedletter):
global ans
if howmanyplaced == num:
ans += 1
return ans
for i in range(0, len(mylist)):
if mylist[i][0] == allowedletter and used[i] == False:
allowedletter = mylist[i][-1]
used[i] = True
place(howmanyplaced+1, allowedletter)
used[i] = False
num = int(input())
mylist = []
for l in range(0, num):
i = input()
used[l] = False
mylist.append(i)
for k in range(0, len(mylist)):
used[k] = True
place(1, mylist[k][-1])
used[k] = False
print(ans)