What is wrong in the code make me correct

Scanner scn = new Scanner(System.in);
int n =scn.nextInt();
int [] arr = new int[n];
for(int i=0 ; i<n ; i++)
{
arr[i]=scn.nextInt();
}
int t = scn.nextInt();
sum(arr , 0 , t ,0, “”);
}
public static void sum(int[] arr , int vidx , int target ,int sum, String ans)
{
Arrays.sort(arr);
if(vidx==arr.length)
{
if(sum==target && ans.length()!=0)
{
System.out.println(ans);
// System.out.print(" ");
}
return;
}
// not include
sum(arr , vidx+1 , target , sum,ans);
// include
sum(arr , vidx+1 , target ,sum+arr[vidx], ans+arr[vidx]);
}
}

Hey Gautam Kapoor,

First of all you need not sort the array in every backtracking call. Sorting it once will work too.

Secondly, there should be no duplicate combinations in the result. You need to add that case in the result that at every level we use the element only once. Try to incorporate this case. Hint: find a way to check the the previously used element in every backtracking level. (For loop might help :thinking:)

Please share your code using the online IDE, as it is easier to debug it that way.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.