Today, I spent most of my time working on backtracking problems. For anyone that isn’t sure, backtracking is a method that incrementally builds potential solutions to problems and abandons those solutions as soon as it determines the approach is invalid. In fewer words, the algorithm builds
Here’s one I worked on today: Factor Combinations.
Write a function that takes an integer n and return all possible combinations of its factors.
Numbers can be regarded as product of its factors. For example,
Note
Each combination’s factors must be sorted ascending, for example: The factors of 2 and 6 is [2, 6], not [6, 2].
You may assume that n is always positive.
Factors should be greater than 1 and less than n.
Approach
Again, I like to start with these problems by walking through examples. Here’s one iteration using 8 as an example.
So, what happens next?
From the walkthrough, our algorithm becomes clear.
While this backtracking solution works, it seems highly inefficient as there seems to be a good amount of rework. Honestly, this seems ripe for dynamic programming (think bottom up). Imagine this list
Given [2, 4], we should be able to deduce [2, 2, 2] because we know the factors for 4. Well, that’s for another day!