ALGORITHM:
The problem is to find all combination of letters in a string ,the question should not be mistaken with permutation of string.To find all combinations of a string we follow a simple method: take each element and and group it with rest of the elements and do the same for thus formed new groups.
So this logic can be implemented using a recursive
algorithm :
-
Take each group(each elements in beginning) and form new groups for each group by combining it with the rest of elements and repeat this procedure for each newly formed groups until the group size becomes equal to the string size.
CODE:
import java.util.Scanner;public class comb{
static void printArray(char[] a,int len){
for (int i=0;i<=len;i++)
System.out.print(a[i]);
System.out.println();
}
static void printCombination(char[] a,char[] b,int aBeg,int bEnd){
for(int i=aBeg;i<a.length;i++){
b[bEnd+1]=a[i];
printArray(b,bEnd+1);
if(i<a.length-1)
printCombination(a,b,i+1,bEnd+1);
}
}
public static void main(String[] args) {
System.out.print("Enter string: ");
char[] a;
Scanner in = new Scanner(System.in);
a=in.next().toCharArray();
char[] b = new char[a.length];
printCombination(a,b,0,-1);
}
}
OUTPUT:
Enter string: abca
ab
abc
ac
b
bc
c
0 comments :
Post a Comment