Explain this subset sum solving function [duplicate]

我的未来我决定 提交于 2019-12-13 08:48:03

问题


This chunk of code is the function that solves a variant of a subset sum problem, but I dont really understand how it gets the answer.

The function returns the subset sum that's closest to the value, if its the same as the value then it just return the value, if two subsets sums are equally close to the value then return the greater sum.

This is it

public static List<int> SolveSubsetSum(int value, IEnumerable<int> xs) 
{
    int b = 2*value+1;
    List<int>[] cols = new List<int>[b];
    cols[0] = new List<int>();
    foreach(int xi in xs) {
        for(int s = b-xi-1; s >= 0; s--) {
            if(cols[s+xi] == null && cols[s] != null) {
               List<int> cln = new List<int>(cols[s]);
               cln.Add(xi);
               cols[s+xi] = cln;
            }
        }
    }
    for(int d = 0; d <= value; d++) {
        if(cols[value+d] != null) {
            return cols[value+d];
        }
        else if(cols[value-d] != null) {
            return cols[value-d];
        } 
    }
    return cols[0];
}

I understand the standard stuff, but I have no clue whats going on in the loops.

My main questions are

  • Why does it need an array of 2*value+1 collections ?

  • Whats going on in the loops ?


回答1:


Somehow, the code in your question is an exact copy of this (my1) answer that implemented this algorithm. I agree that the algorithm itself is not new, but both the structure of the code as well as the variables indicate copying. If you had read the question (and answer) carefully, you could have found out that the problem being solved is the closest subset sum problem. This means that in case no such set can be constructed, you return the set with the smallest difference.

Now since such set can be larger that the requested sum, you need at most 2 K+1 collections with K the requested number, because it is possible that the smallest number in your collection is K-1. Say for instance that the given numbers are {2,5,8,10} and you wish to construct a subset of 6, than the nearest subset sum is {2,5}. You need enough "collections" to store subsets that can be larger.

What's going on in the loops is explain in the linked answer.

1 Who wrote the answer is irrelevant, nevertheless is it easier to detect your own work.



来源:https://stackoverflow.com/questions/34275612/explain-this-subset-sum-solving-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!