子集和解决方案长度

时间:2015-04-10 14:07:50

标签: logic dynamic-programming np-complete

我使用以下逻辑来解决此问题中描述的子集求和问题:Total sum from a set (logic)。它正在工作,每次都会给我一个随机的解决方案,问题是我只需要具有特定数量项目的解决方案。例如:

[2,3,4,6,3] //Set of values
SUM = 6

我能得到的当前解决方案是:

[4,2]
[6]
[3,3]

但是如果我需要这种方法来随机返回一个带有(例如)2个项目的解决方案呢?

1 个答案:

答案 0 :(得分:1)

万一有人需要这个,我终于找到了最后的修改。

正如本post所示,矩阵(或在本例中为立方体)需要填充此逻辑:

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)

这里是Obj-C中的公式,它找到一个具有确切元素数量的随机解决方案:

- (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;
}

干杯:)

相关问题