0-1 Backpack on an infinite integer array?

Given an infinite positive integer array or say a stream of positive integers, find out the first five numbers whose sum is twenty.

After reading the problem statement, it at first seems like a problem 0-1 Knapsack, but I'm confused about what can be used 0-1 Knapsack algofor a stream of integers. Suppose I am writing a recursive program for the indicated problem.

int knapsack(int sum, int count, int idx)
{
    if (sum == 0 && count == 0)
        return 1;

    if ((sum == 0 && count != 0) || (sum != 0 && count == 0))
        return 0;

    if (arr[idx] > 20) //element cann't be included.
        return knapsack(sum, count idx + 1);

    return max(knapsack(sum, count, idx +1), knapsack(sum - arr[idx], count -1, idx + 1));
} 

Now that the above function will call an infinite array, the first call to the maxie function knapsack(sum, count, idx +1)will never return, as it will continue to ignore the current element. Even if we change the order of the call in the function max, there is a chance that the first call will never return. Is there any way to apply knapsackalgo in such scenarios?

+5
source share
2 answers

, .

20 , .

def update(dictlist, num):
    dk = dictlist.keys()
    for i in dk:
        if i+num <=20:
            for j in dictlist[i]:
                listlen = len(dictlist[i][j]) + 1
                if listlen >5:
                    continue
                if i+num not in dictlist or listlen not in dictlist[i+num]:
                    dictlist[i+num][listlen] = dictlist[i][j]+[num]
    if num not in dictlist:
        dictlist[num]= {}
    dictlist[num][1] = [num]
    return dictlist

dictlist = {}
for x in infinite_integer_stream:
    dictlist = update(dictlist,x)
    if 20 in dictlist and 5 in dictlist[20]:
        print dictlist[20][5]
        break

, . dictlist [i] [j] j, i.

+5

Delphi:

var
  PossibleSums: array[1..4, 0..20] of Integer;
  Value, i, j: Integer;
  s: string;
begin
  s := '';
  for j := 1 to 4 do
    for i := 0 to 20 do
      PossibleSums[j, i] := -1;
  while True do begin
    Value := 1 + Random(20); // stream emulation
    Memo1.Lines.Add(IntToStr(Value));

    if PossibleSums[4, 20 - Value] <> -1 then begin
    //we just have found 5th number to make the full sum
      s := IntToStr(Value);
      i := 20 - Value;
      for j := 4 downto 1 do begin
        //unwind storage chain
        s := IntToStr(PossibleSums[j, i]) + ' ' + s;
        i := i - PossibleSums[j, i];
      end;
      Memo1.Lines.Add(s);
      Break;
    end;

    for j := 3 downto 1 do
      for i := 0 to 20 - Value do
        if (PossibleSums[j, i] <> -1) and (PossibleSums[j + 1, i + Value] = -1) then
          PossibleSums[j + 1, i + Value] := Value;

    if PossibleSums[1, Value] = -1 then
      PossibleSums[1, Value] := Value;
  end;
end; 

:

4
8
9
2
10
2
17
2
4 2 10 2 2
0

All Articles