Knapsack - brute force algorithm

前端 未结 2 2027
不知归路
不知归路 2021-02-12 23:08

I have found this code to solve Knapsack Problem using brute force mechanism (this is mostly for learning, so no need to point out dynamic is more efficient). I got the code to

2条回答
  •  情深已故
    2021-02-12 23:30

    Apparently the code parts in question are checks for a certain bit being set, as indicated by the comments. The condition

    ((i >> j) & 1) != 1
    

    is true if and only if the j-th bit of i is zero; the condition

    ((bestPosition >> j) & 1) == 1
    

    is true if and only if the j-th bit of bestPosition is one. Concerning the bigger picture, apparently the implementation uses int to model a set of items, where the j-th bit is set if and only if the j-th item is included in the set; consequently, membership tests can be done by bit checks. The implementation enumerates all subsets of the items (using int to represent them) to perform exhaustive search.

    Note that the Delphi implementation for sets uses the same approach, but hides the bit indexing from client code.

提交回复
热议问题