Linear algorithm to find minimum subset sum over a threshold

前端 未结 2 652
孤城傲影
孤城傲影 2021-01-14 18:04

I have a collection of N positive integers, each bounded by a (relatively small) constant C. I want to find a subset of these numbers with the smallest sum greater than (or

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-14 18:36

    Well one solution is to:

    T = {0}
    
    for x in V
       for t in T
           T.insert(x+t)
    
    for i in K to max(T)
       if (T.contains(i))
           return i
    
    fail
    

    This gives you the size of the subset, but you can adapt to output the members.

    The maximum size of T is O(N) (because of C bound), so the running time is O(N^2) and the space is O(N). You can use a bit array of length NC as the backing store of T.

提交回复
热议问题