📜  sinh nhi phan c++ (1)

📅  最后修改于: 2023-12-03 15:20:08.831000             🧑  作者: Mango

Sinh nhi phan in C++

Sinh nhi phan is a technique used to generate all possible binary strings of a given length. In C++, we can implement this using recursion.

Implementation
void sinhNhiPhan(int n, string output) {
    // Base case: If the length of the output is equal to n,
    // print the output and return.
    if (output.length() == n) {
        cout << output << endl;
        return;
    }
    
    // Recursively append 0 and 1 to the output.
    sinhNhiPhan(n, output + '0');
    sinhNhiPhan(n, output + '1');
}

The sinhNhiPhan function takes two arguments - n, which is the length of the binary strings to be generated, and output, which is a string that is initially empty.

The function first checks if the length of the output string is equal to n. If it is, it means that we have generated a binary string of length n, so we print that string and return.

If the length of the output string is less than n, we recursively call the sinhNhiPhan function twice - once with the output string appended with 0, and once with the output string appended with 1. This generates all possible binary strings of length n.

Example

Let's say we want to generate all possible binary strings of length 3. We can do this by calling the sinhNhiPhan function with n=3 and an empty output string.

sinhNhiPhan(3, "");

This will generate the following output:

000
001
010
011
100
101
110
111
Conclusion

Sinh nhi phan is a simple and powerful technique to generate all possible binary strings of a given length. With the implementation provided in this article, you can easily generate these strings in C++.