I have written the program but it is failing all the test cases. Could you please help me get this fixed.
Could you please help me how to solve this program
I have shared my code. please check and help me.
@indrabijaynarayan bro plenty wrong with your code, no need for that extra intermediate method just use a static arraylist that’s all, then two calls, i.e choose not choose, no need to complex things, I have corrected and refactored your code, check it below. Close this doubt by marking it resolved and rate full bro!
import java.util.*;
public class Main {
public static List result;
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int size = sc.nextInt();
int [] arr = new int[size];
for (int n=0;n<size;n++){
arr[n] = sc.nextInt();
}
int num = sc.nextInt();
result = new ArrayList<>();
Arrays.sort(arr);
toFindCombination("", arr, 0, num, 0);
for(int j=0;j<result.size();j++){
System.out.println(result.get(j));
}
}
private static void toFindCombination(String combination, int[] arr, int cs, int num, int sI) {
// TODO Auto-generated method stub
if(cs == num){
if(!result.contains(combination))
result.add(combination);
return;
}
if(sI == arr.length) {
return;
}
toFindCombination(combination + arr[sI] + " ", arr, cs + arr[sI], num, sI+1);
toFindCombination(combination, arr, cs, num, sI+1);
}
}