[new version]2nd LeetCode: readBinaryWatch
Progress by replacing 1 and 0 s (Python3)
The main algorithm in this problem is listing all the possible combinations of K binary ‘1’s and 10-K binary ‘0’s without repetition.
In the 1st version, I used combinations(list,n) (convert n out of the list to 1) to solve this problem.
This time I want to try to list the combination myself by exchanging 1s and 0s.
The solution is as follows:
- Generate a series containing first K 1’s and 10-K 0's.
The maximum amount of exchange is min(K,10-K) =>E - Define a function with recursion:
a. If currently exchange more than E times, return the current list of timings
b. Elsewise, create a new series by exchange a ‘1’ with a ‘0’ without repetition.
c. The order of exchanging ranged from the X'th 1 to the last 1, from the Y’th 0 to the last 0.
d. If the represented time does not exceed 0:00~11:59, store this series on the list.
e. After exchanging, re-execute this function with new exchange location ([location of first ‘0’]+1,[ location of first ‘1’] +1) and marked that it has been exchange e times. In this way, it will start exchanging from the next 1 and the next 0 if exchanging were experienced. - Execute the function and return the final list that shows all possible times that can be expressed by K ‘1’s.
https://leetcode.com/problems/binary-watch/discuss/602913/Python3-solution-using-digit-exchanging