问题:
任何数都能分解成2的幂,比如
7=1+1+1+1+1+1+1
=1+1+1+1+1+2
=1+1+1+2+2
=1+2+2+2
=1+1+1+4
=1+2+4
共有6种分解方式,设f(n)为任意正整数可能分解总数,比如f(7)=6
写个算法,输入数,求出其分解的总数。
思路:
先按照树形结构,把一个数可能的2的幂的子数记录下来,比如7拆分成7个1,3个2,1个4。从高到底遍历所有可能的搭配。
import math
import copy
def get_distribute_for_number(number):
distribute = {}
distribute[0] = number
for i in range(0, int(math.log(number, 2) + 1)):
if i not in distribute:
break
count_i = distribute[i]
while count_i >= 2:
count_i -= 2
if i + 1 not in distribute:
distribute[i + 1] = 0
distribute[i &