Skip to main content

Get Subsequence

 1. You are given a string str.

2. Complete the body of getSS function - without changing signature - to calculate all subsequences of str.
Use sample input and output to take idea about subsequences.
Input Format
A string str
Output Format
Contents of the arraylist containing subsequences as shown in sample output
Constraints
0 <= str.length <= 20
Sample Input
abc
Sample Output
[, c, b, bc, a, ac, ab, abc]

Solution:

import java.io.*;
import java.util.*;

public class Main {

    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        ArrayList<String> res = new ArrayList<>();
        res = gss(str);
        System.out.println(res);
    }

    public static ArrayList<String> gss(String str) {
        ArrayList<String> res = new ArrayList<>();
        if(str.length() == 0){
            res.add("");
            return res;
        }
        
        String ch = str.substring(0,1);
        String subStr = str.substring(1);
        ArrayList<String> it_res = gss(subStr);
        
        for(String s:it_res)
            res.add(s);
        
        for(String s:it_res)
            res.add(ch+s);
            
        return res;
    }

}

Comments