Given an array of integers and number num.
I need to write a function public static int printExpr(int[] a, int num)
The function should print all the combinations that can give the number num with + or - operators, and to return the number of combinations.
The solution should be recursive
For example, for the given array:
{1, 3, 6, 2} and num=4
The output should be:
+3+1=4
+6-3+1=4
+2+3-1=4
+2+6-3-1=4
-2+6=4
5
My attempt:
public static void main(String[] args) {
int[] a = {1, 3, 6, 2};
System.out.println("\n" + printExpr(a, 4));
}
public static int printExpr(int[] a, int num) {
return printExpr(a, num, 0, 0, "");
}
public static int printExpr(int[] a, int num, int i, int sum, String s) {
if (i < 0 || i >= a.length)
return 0;
if (num == sum) {
System.out.println(s+"=4");
return 1 + printExpr(a, num, i , 0, "") ;
}
return printExpr(a, num, i + 1, sum, s + "")+printExpr(a, num, i + 1, sum + a[i], s + "+" + a[i]) + printExpr(a, num, i + 1, sum - a[i], s + "-" + a[i]) ;
}
My output:
+1+3=4
+1-3+6=4
2
I think that this question is kind of SubsetSum.
What am I missing?
Note LinkedList, HashSet, etc. are not allowed.