Skip to content
Advertisement

printing all subsequences of an array using recursion in JAVA

The following code for above requirement. However I am not getting proper output. There is problem with input list that I am passing in recursion

import java.util.ArrayList;
import java.util.Collections;

public class abc
{
    
    public static void m(ArrayList<Integer> op, ArrayList<Integer> ip) {
       if(ip.size()==0) {
           System.out.println(op);
           return;
       }
       ArrayList<Integer> l1=new ArrayList<Integer>();
       ArrayList<Integer> l2=new ArrayList<Integer>();
       l1.addAll(op);
       l2.addAll(op);
       l1.add(ip.get(0));
       ip.remove(0);
       m(l2,ip);
       m(l1,ip);
    }

    public static void main(String[] args) {
        Integer [] z = {1,3,2};
        ArrayList<Integer> ip=new ArrayList<Integer>();
        Collections.addAll(ip, z);
        ArrayList<Integer> op=new ArrayList<Integer>();
        m(op,ip);
    }
}

Advertisement

Answer

The problem is not, like you said in your comment, that the list ip keeps elements of the previous function call. The problem is that you don’t create a new arraylist as ip parameter for the next function call, meaning, as it is call by reference, that you remove the elements of one function call already in the other function call. You can fix this by just creating a new array list for the new function call, like you already to for op. However you could also use this:

 m(l2,new ArrayList<>(ip));
 m(l1,new ArrayList<>(ip));

so you don’t have to use an extra addAll() 😉

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement