简体   繁体   English

生成所有n位的字符串,考虑A [0..n-1]是大小为n的数组

[英]Gen­er­ate All Strings of n bits, con­sider A[0..n-1] is an array of size n

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)? 为什么在打印第一组值(我认为应该为零)后将n设置为1? Please explain. 请解释。

The values you are passing are (n-1). 您传递的值为(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. 因此,当它输出第一组值时,函数中n的值是0,但是当它从该递归中出来时,它的值为1,因为您将参数(n-1)传递为0。函数将获取n的原始值为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. 该程序首先将第(n-1)th索引元素设置为0 ,然后调用next level recursionprint此设置值,然后执行此操作,然后再次将第(n-1)th索引元素设置为1 ,然后调用next级别递归以打印此设置值。

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. 为了打印所有由01组成的字符串,此程序只是首先将第(n-1)个值设置为0(在基本情况下,其值将被打印为0),然后在(n -1)值以打印此设置值。 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. 因此nBits(n)将第(n-1)th值设置为0nBits(n-1)将第(n-2)th值设置为0 ,依此类推。在基本情况下,将在所有位置打印0

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... 在基本情况下打印值0000...之后,在nBits(1)索引为0th数组元素设置为1 ,然后通过调用nBits(0)进行打印以打印1000...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM