Explain this subset sum function

This piece of code is a function that solves a variant of the problem with a subset, but I really don't understand how it gets the answer.

The function returns the sum of the subset that is closest to the value if it matches the value, and then returns the value if two sums of the subsets are equally close to the value, and then return a large sum.

It's him

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 don't know what happens in loops.

My main questions are:

  • Why do we need an array of collections 2*value+1?

  • What happens in cycles?

-1
source share
1 answer

-, ( 1) , . , , , . ( ), , , , . , , , .

, , , 2 K + 1 K , , - K-1. , , {2,5,8,10} 6, {2,5}. "" , .

, , .

1 , , .

+3

Source: https://habr.com/ru/post/1619979/


All Articles