Click here to Skip to main content
15,887,485 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm currently new to recursion and don't know much about backtracking. I'm looking for help with a backtracking solution to reach the required runtime.
My current code can run for 9 letters, more than that and it won't run.
The problem is as below:
Imaging that you have n cards, which will be stored as a string s. Each of the cards has an upper case letter on it. Return the number of possible non-empty sequences of letters you can make using the cards.
Runtime: 5s
Test case:
1≤𝑛≤15
Input: string
Output: integer

Example 1:

Input: ‘XXY’
Output: 8

Analysis: you can make ‘X’, ‘Y’, ‘XY’, ‘YX’, ‘XX’, ‘XXY’, ‘XYX’, ‘YXX’ 


What I have tried:

Python
<pre>class Solution:
    def Q1(self, s: str) -> int:
        def subsetsWithDup(nums):
            nums.sort()
            result = []

            def subset(S, sub):
                result.append(sub)

                for i in range(len(S)):
                    if i > 0 and S[i] == S[i - 1]:
                        continue

                    subset(S[i + 1:], sub + [S[i]])

            subset(nums, [])
            return result

        def permute(nums):
            if len(nums) == 0:
                return []

            if len(nums) == 1:
                return [nums]

            result = []

            for i in range(len(nums)):
                m = nums[i]
                sublst = nums[:i] + nums[i + 1:]

                for p in permute(sublst):
                    result.append([m] + p)

            return result

        nums = list(s)
        subsets = subsetsWithDup(nums)
        result_set = set()

        for subset in subsets:
            perms = permute(subset)
            for perm in perms:
                result_set.add(''.join(perm))

        return len(list(result_set))
Posted
Updated 24-Oct-23 1:28am
v2

Quote:
My current code can run for 9 letters, more than that and it won't run.
"It doesn't work" is probably the most useless problem report we get - and we get it a lot. It tells us nothing about what is happening, or when it happens.
So tell us what it is doing that you didn't expect, or not doing that you did.
Tell us what you did to get it to happen.
Tell us any error messages.

But ... given that 8! is 40320, 9! is 362880 and 10! is 3628800, the most likely reason is you have exceeded the stack size and you app fails with a stack overflow error - because each time you recursively call your function you use a not-insignificant chunk of stack space. And since you loop loads inside the recursive part, it's a good guess that that causes it.

And also causes your app to run like a stunned slug on Mogadon as the number of characters rises ...

Use the debugger, and see exactly what it is doing.
 
Share this answer
 
Comments
li wilde 22-Oct-23 9:56am    
Maybe there is some problem with my wording, I mean it doesn't satisfy the requirement to run in 5 seconds because the given condition is 15 or less to run in 5 seconds, my code is running, but I would like to ask for an optimisation that takes less time
OriginalGriff 22-Oct-23 10:29am    
If you "mean something", say it. Remember that we can't see your screen, access your HDD, or read your mind - we only get exactly what you type to work with - we get no other context for your project.
You want a faster system? Easy: throw away the whole idea and start again without recursion. Think about the problem and what might shortcut the whole operation.
Hint: start by finding the number of distinct values ...
Please, take a look at Carlo's article: Recursive Permutations in Python[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900