Recursion subset or subsequence

public class Main
{
	public static void main(String[] args) {
		substring("", "abc");
	}
	
	public static void substring(String p, String up) {
	    if(up.isEmpty()) {
	        System.out.println(p);
	        return;
	    }
	    
	    char ch = up.charAt(0);
	    
	   // take it or ignore it
	   substring(p+ch, up.substring(1));
	   substring(p, up.substring(1));
	}
}

Return ArrayList

import java.util.*;
public class Main
{
	public static void main(String[] args) {
		System.out.println(substring("", "abc"));
	}
	
	public static ArrayList<String> substring(String p, String up) {
	    if(up.isEmpty()) {
	        ArrayList<String> list = new ArrayList<>();
	        list.add(p);
	        return list;
	    }
	    
	    char ch = up.charAt(0);
	    
	   // take it or ignore it
	   ArrayList<String> left = substring(p+ch, up.substring(1));
	   ArrayList<String> right = substring(p, up.substring(1));
	   
	   left.addAll(right);
	   return left;
	}
}

Leave a Comment