Use this to learn the idea, then write your own version.
123 4import collections5 6 78class Solution(object):9 def countSequences(self, nums, k):10 """11 :type nums: List[int]12 :type k: int13 :rtype: int14 """15 LOOKUP = {1:(0, 0, 0), 2:(1, 0, 0), 3:(0, 1, 0), 4:(2, 0, 0), 5:(0, 0, 1), 6:(1, 1, 0)}16 def factors(x):17 cnt2 = 018 while x%2 == 0:19 x = 220 cnt2 += 121 cnt3 = 022 while x%3 == 0:23 x = 324 cnt3 += 125 cnt5 = 026 while x%5 == 0:27 x = 528 cnt5 += 129 return (cnt2, cnt3, cnt5) if x == 1 else (-1, -1, -1)30 31 def count(nums):32 dp = collections.defaultdict(int)33 dp[0, 0, 0] = 134 for x in nums:35 new_dp = collections.defaultdict(int)36 d2, d3, d5 = LOOKUP[x]37 for (c2, c3, c5), c in dp.iteritems():38 new_dp[c2, c3, c5] += c39 new_dp[c2+d2, c3+d3, c5+d5] += c40 new_dp[c2-d2, c3-d3, c5-d5] += c41 dp = new_dp42 return dp43 44 c2, c3, c5 = factors(k)45 if c2 == -1:46 return 047 left = count(nums[:len(nums)2])48 right = count(nums[len(nums)2:])49 return sum(d*right[c2-d2, c3-d3, c5-d5] for (d2, d3, d5), d in left.iteritems())50 51 525354import collections55 56 5758class Solution2(object):59 def countSequences(self, nums, k):60 """61 :type nums: List[int]62 :type k: int63 :rtype: int64 """65 LOOKUP = {1:(0, 0, 0), 2:(1, 0, 0), 3:(0, 1, 0), 4:(2, 0, 0), 5:(0, 0, 1), 6:(1, 1, 0)}66 def factors(x):67 cnt2 = 068 while x%2 == 0:69 x = 270 cnt2 += 171 cnt3 = 072 while x%3 == 0:73 x = 374 cnt3 += 175 cnt5 = 076 while x%5 == 0:77 x = 578 cnt5 += 179 return (cnt2, cnt3, cnt5) if x == 1 else (-1, -1, -1)80 81 def count(nums):82 dp = collections.defaultdict(int)83 dp[0, 0, 0] = 184 for x in nums:85 new_dp = collections.defaultdict(int)86 d2, d3, d5 = LOOKUP[x]87 for (c2, c3, c5), c in dp.iteritems():88 new_dp[c2, c3, c5] += c89 new_dp[c2+d2, c3+d3, c5+d5] += c90 new_dp[c2-d2, c3-d3, c5-d5] += c91 dp = new_dp92 return dp93 94 c2, c3, c5 = factors(k)95 if c2 == -1:96 return 097 dp = count(nums)98 return dp[c2, c3, c5]99