A non-recursive trick for subsets generation

The problem in this post is related to subsets, and the solution shows a nice trick to avoid mystical recursive solutions. The enumeration for the problem is simple: given a set S of numbers (integers) and a target number N, print all the subsets S' of S such that Summation(S') = N.
The trick to generate the subsets lies in the binary representation of a number. Suppose that we want to generate all the subsets of a set with 3 elements. We know from basic set theory that the number of subsets of this set is 2^3, also known as 8. Now let's see the binary representation of all the numbers from 0 to 7:

0 = 0 0 0
1 = 0 0 1
2 = 0 1 0
3 = 0 1 1
4 = 1 0 0
5 = 1 0 1
6 = 1 1 0
7 = 1 1 1

The bits interpretation here should be: "if the bit is 1, then the element at that position belongs to the subset". Hence take for instance the number 3:

3 = 0 1 1

Since our original set has 3 elements, say {a,b,c}, this third subset should contain only elements b and c since their respective bits are 1.

Hence in other words, to generate the subsets of a set, the high-level algorithm should be:

For all numbers k from 0 to (2^len(set)) - 1
For all the bits i of k
if i is 1, add the corresponding element to the subset

Exponential in time, but avoids the overhead of recursive calls. Here is the code showing how to do this for the original problem posted:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SubSetAddingToNumberNamespace
{
class Program
{
static void Main(string[] args)
{
int[] set = { 1, 7, -3, 9, 6, -8, 12, 11, 5, -4, 2, 17 };
int target = 67;

SubSetAddingToNumber(set, target);
}

static void SubSetAddingToNumber(int[] set,
int target)
{
if (set == null)
{
return;
}

int powerSetCardinality = (int)Math.Pow(2, set.Length);
for (int i = 0; i < powerSetCardinality; i++)
{
int n = i;
int partialSum = 0;
LinkedList<int> subSet = new LinkedList<int>();
int index = 0;
while (n > 0)
{
if (n % 2 == 1)
{
subSet.AddLast(set[index]);
partialSum += set[index];
}
n /= 2;
index++;
}

if (partialSum == target)
{
int count = 0;
foreach (int item in subSet)
{
if (item < 0)
{
Console.Write("({0})", item);
}
else
{
Console.Write(item);
}
if (count < subSet.Count - 1)
{
Console.Write("+");
}
count++;
}
Console.WriteLine("={0}", target);
}
}
}
}
}

With this output:

7+たす9+たす6+たす12+たす11+たす5+たす17=67
1+7+(-3)+9+たす6+たす12+たす11+たす5+たす2+たす17=67

Comments

  1. That's a great way to solve subset problem and the way I solved the problem when I wasn't very comfortable with recursion. The only thing that's worth mentioning is that in C# int is 32bit, so the set cannot have a size greater than 31 (or 32 with extra care for the sign bit). To deal with bigger sets BigInteger could be used.

    Reply Delete
    Replies
    1. Good point! Although even slightly bigger numbers will make this solution spin forever (think about a set of size 64). I'm positive there must be a DP solution to this problem.

      Delete
    2. Forget about DP, the problem is NP-complete http://en.m.wikipedia.org/wiki/Subset_sum_problem

      Delete

Post a Comment

[フレーム]

Popular posts from this blog

Quasi FSM (Finite State Machine) problem + Vibe

Not really an FSM problem since the state isn't changing, it is just defined by the current input. Simply following the instructions should do it. Using VSCode IDE you can also engage the help of Cline or Copilot for a combo of coding and vibe coding, see below screenshot. Cheers, ACC. Process String with Special Operations I - LeetCode You are given a string  s  consisting of lowercase English letters and the special characters:  * ,  # , and  % . Build a new string  result  by processing  s  according to the following rules from left to right: If the letter is a  lowercase  English letter append it to  result . A  '*'   removes  the last character from  result , if it exists. A  '#'   duplicates  the current  result  and  appends  it to itself. A  '%'   reverses  the current  result . Return the final string  result  after processing all char...

Shortest Bridge – A BFS Story (with a Twist)

Here's another one from the Google 30 Days challenge on LeetCode — 934. Shortest Bridge . The goal? Given a 2D binary grid where two islands (groups of 1s) are separated by water (0s), flip the fewest number of 0s to 1s to connect them. Easy to describe. Sneaky to implement well. 🧭 My Approach My solution follows a two-phase Breadth-First Search (BFS) strategy: Find and mark one island : I start by scanning the grid until I find the first 1 , then use BFS to mark all connected land cells as 2 . I store their positions for later use. Bridge-building BFS : For each cell in the marked island, I run a BFS looking for the second island. Each BFS stops as soon as it hits a cell with value 1 . The minimum distance across all these searches gives the shortest bridge. 🔍 Code Snippet Here's the core logic simplified: public int ShortestBridge(int[][] grid) { // 1. Mark one island as '2' and gather its coordinates List<int> island = FindAndMark...

Classic Dynamic Programming IX

A bit of vibe code together with OpenAI O3. I asked O3 to just generate the sieve due to laziness. Sieve is used to calculate the first M primes (when I was using Miller-Rabin, was giving me TLE). The DP follows from that in a straightforward way: calculate the numbers from i..n-1, then n follows by calculating the min over all M primes. Notice that I made use of Goldbach's Conjecture as a way to optimize the code too. Goldbach's Conjecture estates that any even number greater than 2 is the sum of 2 primes. The conjecture is applied in the highlighted line. Cheers, ACC. PS: the prompt for the sieve was the following, again using Open AI O3 Advanced Reasoning: " give me a sieve to find the first M prime numbers in C#. The code should produce a List<int> with the first M primes " Minimum Number of Primes to Sum to Target - LeetCode You are given two integers  n  and  m . You have to select a multiset of  prime numbers  from the  first   m  pri...