2

Imagine a non-ordered singularly-linked structure with integer nodes (ex. 5 -> 8 -> 10 -> 2 -> 7), and a given sum (ex. 15). How could I find the first subset to equate to the sum recursively? In this example, the answer would be 5 -> 8 -> 2 (5 -> 10 or 8 -> 7 would also be an answer, but not the first). I have a method "node f(node, sum)":

if node == null
   return null
else if node.value <= target
   return new Node(node.item, f(node.next, sum - node.value)
else
   return f(node.next, sum)

However, this will return subsets that are less than or equal to the sum, not exactly the sum. How can I create an exact algorithm?

iso
  • 31
  • 7

2 Answers2

2

Backtrack is what you are looking for. :)

Also you have not defined how the subsets should be ordered. Depending on this backtracking and stopping once you find a solution might not work and you will have to implement BFS on possible solutions.

Šimon Kocúrek
  • 1,591
  • 1
  • 12
  • 22
0

I hope below implementation help.

#include <stdio.h>
int N = 5;
int arr[] = {5,8,10,2,7};

bool dfs(int next, int sum)
{
    if(next==N) return false;
    if(sum==0) return true;  //backtrack to get first answer

    //include
    bool r1 = dfs(next+1, sum-arr[next]);

    //non-include
    bool r2 = dfs(next+1, sum);
    return r1||r2;
}

int main(void)
{
    printf("%d\n", dfs(0, 15));
    return 0;
}
CodingLab
  • 1,441
  • 2
  • 13
  • 37