To check whether it can become an integer k, we track prime-exponent vectors instead of doing fraction arithmetic. In this problem we only care about primes {2,3,5} since the number is 1 to 6.
If k contains any other prime factor, it is impossible, return 0.
Then we do the search backwards, process nums from right to left, and at each position, do unchanged, multiple or divide.
When we finish all indices we add the total count by one if the remaining target is 1.
Since the same (idx, v) state appears many times, we use memoization (top-down DP).
Another method is using the meet-in-the-middle technique, where I hear this the first time. For DFS, if hte memorization is bad, we can have extramely large searching space and depth by O(3^n). The meet-in-the-middle technique would store the states in the middle, and do the DFS again in the right and check the final status based of hte left status. In this case the complexity can be reduce to O(3^(n/2)), which is a significant reduction.
An interesting part is that the DP with memo method would not be that bad in practice if hte solution space is highly overlapped, in this case we don’t have lots of depth and state. However, the worst case complexity for meet-in-the-middle might be better.
Code
class Solution {
struct V {
int cnt[3] = {0}; // 2,3,5
bool others = false;
bool isOne() {return cnt[0] == 0 && cnt[1] == 0 && cnt[2] == 0 && !others;}
void mult(const V& v2) {cnt[0] += v2.cnt[0]; cnt[1] += v2.cnt[1]; cnt[2] += v2.cnt[2];}
void div(const V& v2) {cnt[0] -= v2.cnt[0]; cnt[1] -= v2.cnt[1]; cnt[2] -= v2.cnt[2];}
int GetKey(int idx) {
return cnt[0] * 1000000 + cnt[1] * 10000 + cnt[2] * 100 + idx;
}
};
public:
int countSequences(vector<int>& nums, long long k) {
V v = findMap(k);
if(v.others) return 0;
vector<V> fac;
int n = nums.size();
for(int i = 0 ; i < n ; ++i) {
fac.push_back(findMap(nums[i]));
}
return traverse(fac, v, n-1);
}
int traverse(const vector<V>& fac, V& v, int idx) {
if(idx == -1) return v.isOne();
int key = v.GetKey(idx);
if(memo.count(key)) return memo[key];
V cur = fac[idx];
int totalCnt = traverse(fac, v, idx-1);
v.mult(cur);
totalCnt += traverse(fac, v, idx-1);
v.div(cur);
v.div(cur);
totalCnt += traverse(fac, v, idx-1);
v.mult(cur);
memo[key] = totalCnt;
return totalCnt;
}
unordered_map<int, int> memo;
V findMap(long long k) {
const vector<int> f = {2, 3, 5};
V v;
for(int i = 0 ; i < 3 ; ++i) {
while(k % f[i] == 0) {
k /= f[i];
++v.cnt[i];
}
}
if(k != 1) v.others = true;
return v;
}
};