Algorithm for Human Towering

后端 未结 4 1902
悲哀的现实
悲哀的现实 2021-01-02 22:39

In Cracking the Coding Interview, Fourth Edition, there is such a problem:

A circus is designing a tower routine consisting of people standing atop

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-02 22:57

    After first sorting the array by height and weight, my code checks what the largest tower would be if we grabbed any of the remaining tuples in the array (and possible subsequent tuples). In order to avoid re-computing sub-problems, solution_a is used to store the optimal max length from the tail of the input_array.

    The beginning_index is the index from which we can consider grabbing elements from (the index from which we can consider people who could go below on the human stack), and beginning_tuple refers to the element/person higher up on the stack.

    This solution runs in O(nlogn) to do the sort. The space used is O(n) for the solution_a array and the copy of the input_array.

    def determine_largest_tower(beginning_index, a, beginning_tuple, solution_a):
        # base case
        if beginning_index >= len(a):
            return 0
        if solution_a[beginning_index] != -1:   # already computed
            return solution_a[beginning_index]
    
        # recursive case
        max_len = 0
        for i in range(beginning_index, len(a)):
            # if we can grab that value, check what the max would be
            if a[i][0] >= beginning_tuple[0] and a[i][1] >= beginning_tuple[1]:
                max_len = max(1 + determine_largest_tower(i+1, a, a[i], solution_a), max_len)
        solution_a[beginning_index] = max_len
        return max_len
    
    def algorithm_for_human_towering(input_array):
        a = sorted(input_array)
        return determine_largest_tower(0, a, (-1,-1), [-1] * len(a))
    
    a = [(3,2),(5,9),(6,7),(7,8)]
    print algorithm_for_human_towering(a)
    

提交回复
热议问题