public class GenerateAllStrings {
int []arrA;
public GenerateAllStrings(int n)
{
arrA = new int[n];
}
public void nBits(int n)
{
if(n <= 0)
System.out.println(Arrays.toString(arrA));
else
{
arrA[n-1] = 0;
nBits(n-1);
arrA[n-1] = 1;
nBits(n-1);
}
}
public static void main(String[] args) throws java.lang.Exception
{
int n = 3;
GenerateAllStrings i = new GenerateAllStrings(n);
i.nBits(n);
}
}
I am unable to understand recursion in this program. why is n set to 1 after printing the first set of value( I thought it should be zero)? Please explain.
The values you are passing are (n-1). So when it prints the first set of values, the value of n in the function is 0 but when it comes out of that recursion it is 1 since you passed the argument as (n-1) which is 0. Thus coming out of the function it gets the original value of n which was 1.
This program is first setting element at (n-1)th
index to 0
and then calling next level recursion
to print
this setted value and after doing this, it again sets the (n-1)th
index element to 1
and then calling next level recursion to print this setted value.
This sort of logic is happening at each level.
In order to print all the strings consists of 0
and 1
, this program is just first setting the (n-1)th value to 0( Here in the base case it's value will be printed 0) and then calling the recursion on (n-1)th value in order to print this setted value. Therefore nBits(n)
is setting (n-1)th
value to 0
, nBits(n-1)
is setting the (n-2)th
value to 0
and so on.So in the base case, 0
will be printed everywhere.
After printing the value 0000...
in the base case, array element at 0th
index is set to 1
in nBits(1)
and then it's just printed by calling nBits(0)
which prints 1000...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.