project euler 169

http://projecteuler.net/problem=169

Define f(0)=1 and f(n) to be the number of different ways n can be expressed as a sum of integer powers of 2 using each power no more than twice.

For example, f(10)=5 since there are five different ways to express 10:

1 + 1 + 8
1 + 1 + 4 + 4
1 + 1 + 2 + 2 + 4
2 + 4 + 4
2 + 8

What is f(1025)?

我在推导的时候就没有考虑过这种递推形式,然后可耻的搜了一下,用python写了个记忆化搜索。

可以仔细想一下,这是一到打破思维定势的题目。

hint反选可见: 递推的形式是f(x) = f(y) + f(z)

代码反选可见:

memo = {}
def f(x):
    if memo.has_key(x): return memo[x]
    if (x == 0): return 1
    ans = 0;
    if x % 2 == 1:
        ans = f(x // 2)
    else:
        ans = f(x // 2) + f(x//2 - 1)
    memo[x] = ans
    return ans

print (f(10**25))
print("Program finished")
while True: pass

posted on 2011-10-12 22:32  schindlerlee  阅读(398)  评论(0编辑  收藏  举报