https://leetcode.cn/problems/number-of-different-subsequences-gcds/solutions/?orderBy=most_votes
answer :
Because the number of non -empty sequences is as high as
$$
2^n-1
$$
,Back traceability is overtime。May wish to change a perspective,Consider the value domain。
The maximum number of multiple numbers is equal to g,Conversely explaining these numbers are all g Multiple。For example [8,12,6] The maximum number of contracts is 2,These numbers are all 2 Multiple。
So,Can you reverse,enumerate g Multiple呢?
1,2,3,
2,4,6,⋯
3,6,9,⋯
It seems that the running time is a square level,Timeout。
⌊
1
U
⌋
Don’t rush to deny,There are some math here。
set up U=max(nums),So 1 Multiple需要enumerate $⌊U1⌋\left\lfloor\dfrac{U}{1}\right\rfloor⌊
1
U
⌋ $indivual,222 Multiple需要enumerate ⌊U2⌋\left\lfloor\dfrac{U}{2}\right\rfloor⌊2 U ⌋ indivual,……,Add these,Remove it and take it up,have4
$$⌊U1⌋+⌊U2⌋+⋯+⌊UU⌋≤U⋅(11+12+⋯+1U) \left\lfloor\dfrac{U}{1}\right\rfloor + \left\lfloor\dfrac{U}{2}\right\rfloor +\cdots + \left\lfloor\dfrac{U}{U}\right\rfloor \le U\cdot\left(\dfrac{1}{1} + \dfrac{1}{2} + \cdots + \dfrac{1}{U}\right)$$
The one in the bracket on the right is called Harmonic,Can be seen as $$O(logU)O(\log U)O(logU)$$ of,因此enumerate倍数of时间复杂度为 $$O(UlogU)O(U\log U)O(UlogU)$$,不Timeout。
So就enumerate $$i=1,2,⋯ ,Ui=1,2,\cdots,Ui=1,2,⋯,U$ Its multiple,当作子序列middleof数。
子序列middleof数越多,g The smaller it may be,The more likely i。
For example,如果enumerate i=2 Multiple,in 8 and 12 In $$nums\textit{nums}nums$$ middleof,Due to 8 and 12 of最大公约数等于 4,所以无法找到一indivual子序列,Its maximum number i。但如果还have 6 Also $$nums\textit{nums}nums$$ middle,So最大公约数等于 2,so i 就可以是一indivual子序列of最大公约数了。
Code implementation,Need to use hash tables or array,记录每indivual数是否在 $$nums\textit{nums}nums$$ middle,So as to speed up judgment。数组of效率会更高一些。