1

Given an array of integers and a sum, the task is to print all subsets of given array with sum equal to given sum recursively.

Input : arr[] = {2, 3, 5, 6, 8, 10}

sum = 10

Output :

5 2 3

2 8

10

I have tried something please take a look .my code doesn't produce the right output. On running the code it gives no output but also no errors and warning is shown.I dont know where my approach is wrong in my code.

k is sum

si is starting index

public class returnSubsetOfsumK {


private static int[][] subsetsSumK(int input[], int k,int si){      
    //base case
 if(si == input.length ) {
        if(k==0) {
            int ans[][] = {{}};
            return ans;
        }else {
            int ans[][] = {};
            return ans;
        }
    }

    //case 1

    int temp1[][] = subsetsSumK(input, k-input[si], si+1);
    if(temp1.length==0) {
        int ans[][] = {};
        return ans;
    }

    //appending input[si] in output

    int temp3[][] = new int[temp1.length][];

    for(int i = 0;i<temp1.length;i++) {
        temp3[i] = new int[temp1[i].length+1];

    }

    for(int i = 0;i<temp3.length;i++) {
        for(int j = 0;j<temp3[i].length;j++) {
            if(j==0) {
                temp3[i][j] = input[si];
            }else {
                temp3[i][j] = temp1[i][j-1];
            }
        }

    }




    //case 2

    int temp2[][] = subsetsSumK(input, k, si+1);

    if(temp2.length==0) {
        int ans[][] = {};
        return ans;
    }


    //Final Output to add temp3 and temp2;
    int output[][] = new int[temp3.length+temp2.length][];

    for(int i = 0;i<temp3.length;i++) {
        output[i] = new int[temp3[i].length];
    }
    for(int i = temp3.length;i<output.length;i++) {
        output[i] = new int[temp2[i-temp3.length].length];
    }


    for(int i = 0;i<temp3.length;i++) {
        for(int j = 0;j<temp3[i].length;j++) {
            output[i][j] = temp3[i][j];
       }  
    }

    for(int i = temp3.length;i<output.length;i++) {
        for(int j = 0;j<output[i].length;j++) {
            output[i][j] = temp2[i-temp3.length][j];
         }
    }



    return output;
}



public static int[][] subsetsSumK(int input[], int k) {
    // Write your code here
         return subsetsSumK(input, k, 0);

    }





public static void main(String[] args) {
    // TODO Auto-generated method stub

    int input[] = {2,1,3,2};
    int out[][] = subsetsSumK(input, 4); 
    for(int i = 0;i<out.length;i++) {
        for(int j = 0;j<out[i].length;j++) {
            System.out.print(out[i][j]);
         }
        System.out.println();
    }

}

}

0 Answers0