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?
2*value+1
What happens in cycles?
-, ( 1) , . , , , . ( ), , , , . , , , .
, , , 2 K + 1 K , , - K-1. , , {2,5,8,10} 6, {2,5}. "" , .
{2,5,8,10}
6
{2,5}
, , .
1 , , .
Source: https://habr.com/ru/post/1619979/More articles:diff two rpms? - linux - linuxPadding-top в псевдоэлементе не будет работать в Firefox (но в Chrome, Safari) - htmlError authenticating application using link - c #How to record audio in wav format in Swift? - iosConvert bitfield to array - arraysIf the sum of the subset is not equal to the specified value, the sum of the subset closest to the value is c #Bash script - how to read a file line by line when using getopts - bashNodeJS / Express4 endpoint generates corrupt xlsx file - angularjs Родитель не имеет тип ActionSource, тип: com.sun.faces.component.PassthroughElement - jsfXLSX file damaged when sending from Node.js via Restify to Client - node.jsAll Articles