Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8408789
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T23:43:41+00:00 2026-06-09T23:43:41+00:00

This is not homework, I don’t have money for school so I am teaching

  • 0

This is not homework, I don’t have money for school so I am teaching myself whilst working shifts at a tollbooth on the highway (long nights with few customers).

I am trying to implement a simple subset sum algorithm which, given an array of integers, returns a subset of it whose sum equals a desired sum, reporting how many invocations it took to find it.

I did an implementation in Java using Collections but that was very bloated code, even if I was able to return all sets adding up to the desired number as well as telling the function to stop at the first match or not.

The problem I have with this code is as follows: rather than running in 2^n time (that’s correct for such an implementation when no results are found, is it not?) it runs in [2^(n+1)]-1 time; O(2^n) as pointed out by a comment. I can see why that is given that I check for (runningTotal == targetTotal) on a deeper level than I could, essentially adding the extra depth myself, don’t I? I was trying to model the base case as cleanly as possible, let me know if you detect any “code smells”. Should I be breaking as soon as I see that (runningTotal + consider) == targetTotal?

Note: I don’t think this belongs to “Code Review” as I am asking about a particular code line, not the overall approach (if I need to change the approach, so be it, I am doing this to learn).

Here my attempt (is this “passable” C/C++ apart from the lack of optimisation mentioned above?):

#include <iostream>
using namespace std;
bool setTotalling(int chooseFrom[], int nChoices, int targetTotal,
    int chooseIndex, int runningTotal, int solutionSet[], int &solutionDigits,
    int &nIterations) {
  nIterations++;
  if (runningTotal == targetTotal) {
    return true;
  }
  if (chooseIndex >= nChoices) {
    return false;
  }
  int consider = chooseFrom[chooseIndex];
  if (setTotalling(chooseFrom, nChoices, targetTotal, chooseIndex + 1,
      runningTotal + consider, solutionSet, solutionDigits, nIterations)) {
    solutionSet[solutionDigits++] = consider;
    return true;
  }
  if (setTotalling(chooseFrom, nChoices, targetTotal, chooseIndex + 1,
      runningTotal, solutionSet, solutionDigits, nIterations)) {
    return true;
  }
  return false;
}
void testSetTotalling() {
  int chooseFrom[] = { 1, 2, 5, 9, 10 };
  int nChoices = 5;
  int targetTotal = 23;
  int chooseIndex = 0;
  int runningTotal = 0;
  int solutionSet[] = { 0, 0, 0, 0, 0 };
  int solutionDigits = 0;
  int nIterations = 0;
  cout << "Looking for a set of numbers totalling" << endl << "--> "
      << targetTotal << endl << "choosing from these:" << endl;
  for (int i = 0; i < nChoices; i++) {
    int n = chooseFrom[i];
    cout << n << ", ";
  }
  cout << endl << endl;
  bool setExists = setTotalling(chooseFrom, nChoices, targetTotal, chooseIndex,
      runningTotal, solutionSet, solutionDigits, nIterations);
  if (setExists) {
    cout << "Found:" << endl;
    for (int i = 0; i < solutionDigits; i++) {
      int n = solutionSet[i];
      cout << n << ", ";
    }
    cout << endl;
  } else {
    cout << "Not found." << endl;
  }
  cout << "Iterations: " << nIterations << endl;
}
int main() {
  testSetTotalling();
  return 0;
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-09T23:43:43+00:00Added an answer on June 9, 2026 at 11:43 pm

    The point is how to count an “iteration”. Suppose you have the simple case with n=1 targeting a sum that is not zero and not the element you have.

    You call the function and this immediately increments the counter, then you get to the bifurcation and the function calls itself two times (one considering the element and one without considering the element). Each of these call will count 1 so you will end up with a total counter of 3.

    I don’t see anything wrong with this…

    You could add a special check to repeat the test and avoiding call if the numb of remaining choices is zero, but this would require repeating the check. Doing the end check only at recursive call place would not take in account that the function could be called with zero choiches directly. Basically you are “inlining” level 0… but then why stop at level zero and not inlining also level 1?

    If you are looking for speedups note that (assuming all elements are non-negative) if you know that adding all the remaining available numbers still there’s not enough to get to the target then you can avoid doing the check of all possible subset.
    By computing once the total of all remaining numbers from a given index to the end of the list of available elements (that’s an O(n) computation) you can save (2^remaining) iterations.
    Also if the current sum is already too big there’s not point in considering adding other elements either.

    if (targetTotal > runningTotal)
        return false; // We already passed the limit
    if (targetTotal - runningTotal > sumOfAllFrom[choseIndex])
        return false; // We're not going to make it
    

    If you also sort the elements in decreasing order the above optimization can save a lot.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

This is not homework, I don't have money for school so I am teaching
First of all, this is not homework, so please don't tag it as homewrok
First of all, this is not homework! :) Say I have an NSString: the?or?
I have to write this code for a homework assignment but I don't even
I am using NHibernate and this is not a Homework. Suppose I have retrieved
This is not homework . I am interested in setting up a simulation of
This is not homework, I need this for my program :) I ask this
Please note that this is not homework and i did search before starting this
To clarify before I begin, this is NOT homework but rather I am studying
This is not exactly homework but it is related to my studies: A grammar

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.