Given an array of integers, print sums of all subsets in it. Output should be printed in increasing order of sums.
Input :
arr[] = {2, 3}
Output:
0 2 3 5
Input :
arr[] = {2, 4, 5}
Output :
0 2 4 5 6 7 9 11
Input:
The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. The first line of each test case is N, N is the size of array. The second line of each test case contains N space separated values of the array arr[].
Output:
Output for each test case should be space separated sums in increasing order.
Constraints:
1 ≤ T ≤ 100
1 ≤ N ≤ 10
0 ≤ A[i] ≤ 100
Input:
2
2
1 2
3
5 2 1
Output:
0 1 2 3
0 1 2 3 5 6 7 8
My approach:
import java.util.Scanner;
import java.util.Collections;
import java.lang.StringBuffer;
import java.lang.Math;
import java.util.List;
import java.util.ArrayList;
class SubsetSums {
private static List<Integer> subSetSums (int[] arr) {
int len = arr.length;
List<Integer> sums = new ArrayList<>();
sums.add(0);
List<String> binaryNumbers = new ArrayList<>();
int limit = (int)Math.pow(2,len);
for (int i = 1; i < limit; i++) {
String bin = getBinary(i,len);
binaryNumbers.add(bin);
}
/*
for (String str : binaryNumbers) {
System.out.println(str);
}
*/
for (int i = 0; i < binaryNumbers.size() ; i++) {
List<Integer> subSet = new ArrayList<>();
String binary = binaryNumbers.get(i);
for (int j = 0; j < binary.length(); j++) {
if (binary.charAt(j) == '1') {
subSet.add(arr[j]);
}
}
int sum = getSum(subSet);
sums.add(sum);
subSet.clear();
}
Collections.sort(sums);
return sums;
}
private static int getSum (List<Integer> subSet) {
int sum = 0;
for (Integer elem : subSet) {
sum += elem;
}
return sum;
}
private static String getBinary (int num, int len) {
String bin = "";
if (num == 1) {
String zeros = "";
int numZeros = len - 1;
while (numZeros != 0) {
zeros += "0";
numZeros--;
}
return zeros.concat("1");
}
else {
while (num != 0) {
int rem = num%2;
bin += String.valueOf(rem);
num = num/2;
}
bin = new StringBuffer(bin).reverse().toString();
String zeros = "";
int numZeros = len - bin.length() ;
while (numZeros != 0) {
zeros = zeros + "0";
numZeros--;
}
return (zeros.concat(bin));
}
}
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int numTests = sc.nextInt();
while (numTests-- > 0) {
int size = sc.nextInt();
int[] arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = sc.nextInt();
}
List<Integer> finalSums = subSetSums(arr);
for (Integer elem : finalSums) {
System.out.print(elem + " ");
}
System.out.println();
}
sc.close();
}
}
I have the following questions with regards to the above code:
How can I further improve my approach?
Is there a better way to solve this question?
Are there any grave code violations that I have committed?
Can space and time complexity be further improved?
2 3 4 5
, your code returns duplicated results, because 5 is 1+4 or 2+3, 7 is 2+5 or 3+4 and 9 is 2+3+4 or 4+5. Is it by design or is it an error? \$\endgroup\$