Class assignment - In a mathematics class, Teacher ask Alice to find the number of all n digit distinct integers

giving time limit error
how to optimize this code

import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner obj = new Scanner(System.in);
int t = obj.nextInt();
int i=0;
while(i<t)
{
int n = obj.nextInt();
StringBuilder str=new StringBuilder("");
System.out.println("#"+(i+1)+" : "+assign(str,n));

i++;

}
}
public static int assign(StringBuilder str ,int n)
{if(str.length()==n)
{return 1;}
int t1= assign(str.insert(0,β€˜a’), n);
str.deleteCharAt(0);

int t2=0;
if(str.length()>0)
{if(str.charAt(0)!='b')
 {t2=assign(str.insert(0,'b'),n);
 str.deleteCharAt(0);}}
 if(str.length()==0)
 {t2=assign(str.insert(0,'b'),n);
 str.deleteCharAt(0);}
 return t1 + t2;

}

}

int a[n],b[n];
a[0]=1,b[0]=1;
for(int i=1;i<n;i++)
{
a[i]=a[i-1]+b[i-1];
b[i]=a[i-1];
}
return a[n-1]+b[n-1];

the a can be formed by appending a in the last of a’s as well as b’s
b can be formed by appending b in the last of a’s, b can’ be append in the last of b’s

hope this will help u
pls rate my work so that i can improve myself.

1 Like