Problem Statement: Given an array, operate (possibly sum/product) on every possible non-empty subset.
Its helpful in so many contexts if you have no idea to solve the problem optimally. It runs in exponential time.
Given n, m. There are m elements in the array. You have to find the number of ways in which given sum = n can be obtained using non-empty subsets of the array.
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
long long coinChange(int cost[], int m, int n){
char binary[m];
memset(binary, 0, sizeof(binary));
long long x = (long long)pow(2, m) ;
long long i, ans = 0;
for (i = 1; i < x; i++){
int j = m-1;
while (binary[j] != 0 && j >= 0){
binary[j] = 0;
j--;
}
binary[j] = 1;
int k;
long long sum = 0;
for (k = 0; k < m; k++){
if (binary[k] == 1)
sum += cost[k];
}
if (sum == n)
ans++;
}
return ans;
}
int main() {
int n, m;
scanf("%d%d", &n, &m);
int cost[m];
int i;
for (i = 0; i < m; i++)
scanf("%d", &cost[i]);
printf("%lld", coinChange(cost, m, n));
return 0;
}
Its helpful in so many contexts if you have no idea to solve the problem optimally. It runs in exponential time.
Given n, m. There are m elements in the array. You have to find the number of ways in which given sum = n can be obtained using non-empty subsets of the array.
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
long long coinChange(int cost[], int m, int n){
char binary[m];
memset(binary, 0, sizeof(binary));
long long x = (long long)pow(2, m) ;
long long i, ans = 0;
for (i = 1; i < x; i++){
int j = m-1;
while (binary[j] != 0 && j >= 0){
binary[j] = 0;
j--;
}
binary[j] = 1;
int k;
long long sum = 0;
for (k = 0; k < m; k++){
if (binary[k] == 1)
sum += cost[k];
}
if (sum == n)
ans++;
}
return ans;
}
int main() {
int n, m;
scanf("%d%d", &n, &m);
int cost[m];
int i;
for (i = 0; i < m; i++)
scanf("%d", &cost[i]);
printf("%lld", coinChange(cost, m, n));
return 0;
}