I am wondering can powerset problem be transformed and reduced to knapsack problem? It seems to me that they are identical that for example the changes making problem which we can think of it as powerset that every recursive stage I launch 2 recursive calls (one takes the i
th element, and the other one bypass it). I can also solve it with dynamic programming just like knapsack problem, so this makes me wondering if all the powerset problem can be transformed to knapsack problem. Is that correct ?
The following are the code fragment of the coin changes making one with O(2N) time complexity and one with dynamic programming O(N2) runtime.
// O(2^N) time complexity
void bruteforce(int[] coins, int i, int N, String expr)
{
if (i == coins.length) {
if (N == 0)
count++;
return;
}
if (N >= coins[i])
recursion(coins, i, N - coins[i], expr + " " + coins[i]);
recursion(coins, i + 1, N, expr);
}
// O(N^2) time complexity
int dynamicProgramming(int[] coins, int N)
{
int [] dp = new int[N + 1];
dp[0] = 1;
for(int i = 0; i < coins.length; i++)
for(int j = coins[i]; j <= N; j++)
dp[j] += dp[j - coins[i]];
return dp[N];
}
Finding powerset (generating all subsets of a set) can't be done in a way that has a complexity better than O(2n) because there are 2n subsets and merely printing them will take exponential time.
Problems like subset sum, knapsack or coin change are related to powerset because you implicity have to generate all subsets but there is a big difference between them and powerset. In these problems you are only counting some subsets and you aren't required to explicity generate those subsets. For example if the problem asks you to find all the ways to change X dollars to some coins then you can't solve this in linear time because you have to generate all the desired subsets and there could be 2n of them.