问题
I'm using the following logic to solve the subset sum problem as described in this question: Total sum from a set (logic). It is working and it will give me one random solution every time, the problem is that I need only the solutions with an specific amount of items. For example:
[2,3,4,6,3] //Set of values
SUM = 6
The current solutions I can get are:
[4,2]
[6]
[3,3]
But what if I need this method to randomly return only a solution with (for example) 2 items?
回答1:
Just in case somebody needs this, i finally found the final modification.
As suggested in this post the matrix (or in this case, the cube) needs to be filled with this logic:
D(x,i,j) = 0 when x<0 || j<0
D(0,i,0) = 1
D(x,0,j) = 0 when x>0 && j>0
D(x,i,j) = D(x-arr[i],i-1,j-1) + D(x,i-1,j)
Here's the formula in Obj-C that finds one random solution with the exact amount of elements:
- (NSArray *)getSubset
{
NSMutableArray *solution = [[NSMutableArray alloc] init];
int i = (int) self.vals.count; //vals is the array with the values
int j = (int) self.size; //size is the amount of values I want
int x = (int) self.sum; //the objective sum
//the last position has the solutions count
if ([self.matrix[x][i][j] intValue] < 1) {
NSLog(@"No matrix solution");
return nil;
}
while (x>0) {
NSMutableArray *possibleVals = [[NSMutableArray alloc] init];
if ([self.matrix[x][i-1][j] intValue] > 0) {
[possibleVals addObject:[NSNumber numberWithInt:x]];
}
int posR = x - [self.vals[i-1] intValue];
if ((posR >= 0) && ([self.matrix[posR][i-1][j-1] intValue] > 0)) {
[possibleVals addObject:[NSNumber numberWithInt:posR]];
}
int rand = arc4random();
int rIndex = rand % possibleVals.count;
int r = [possibleVals[rIndex] intValue];
if (r != x) {
[solution addObject:[NSNumber numberWithInt:x-r]];
j--; //We only move through j when we've added a value
}
x = r;
i--;
}
return solution;
}
Cheers :)
来源:https://stackoverflow.com/questions/29563596/subset-sum-solution-length