Brick Tower Building Puzzle

前端 未结 2 1809
你的背包
你的背包 2021-01-16 19:27

I\'ve been given a little brainteaser to solve.

The task is to make a function with a single integer parameter. You have to figure out how many different combination

相关标签:
2条回答
  • 2021-01-16 19:55

    Wikipedia gives the generating function for the number of partitions of n with distinct parts as q(n) = product (1+x^k) for k=1..infinity. Given that you exclude the possibility of a single tower, the number of different valid tower arrangements is q(n)-1.

    This gives this neat O(n^2) time and O(n) space program for counting tower arrangements.

    def towers(n):
        A = [1] + [0] * n
        for k in xrange(1, n+1):
            for i in xrange(n, k-1, -1):
                A[i] += A[i-k]
        return A[n] - 1
    
    print towers(200)
    

    The output is as required:

    487067745
    

    To understand the code, one can observe that A stores the first n+1 coefficients of the generating function product(1+x^k) for k=1...infinity. Each time through the k loop we add one more term to the product. We can stop at n rather than infinity, because subsequent terms of the product do not affect the first n+1 coefficients.

    Another, more direct, way to think about the code is to define T(i, k) to be the number of tower combinations (including the single tower) with i blocks, and where the maximum height of any tower is k. Then:

    T(0, 0) = 1
    T(i, 0) = 0 if i > 0
    
    T(i, k) = T(i, k-1)               if i < k
            = T(i, k-1) + T(i-k, k-1) if i >= k
    

    Then one can observe that after j iterations of the for k loop, A contains the values of T(j, i) for i from 0 to n. The update is done somewhat carefully, updating the array from the end backwards so that results are changed only after they are used.

    0 讨论(0)
  • 2021-01-16 20:12

    Imagine calling the function answer(6). Your code returns 2, the correct answer however is 3 (5, 1; 4, 2; 3, 2, 1). Why is this? your code stops when the amount of blocks above the bottom tower is greater than the length of the bottom tower, so it sees 3, 3 and stops, it therefor never considers the combination 3, 2, 1.

    My advice would be to rethink the function, try to take into account the idea that you can stack a number of blocks N on top of a tower that is less than N high.

    0 讨论(0)
提交回复
热议问题