<p>An <strong>n-bit gray code sequence</strong> is a sequence of <code>2<sup>n</sup></code> integers where:</p>

<ul>
	<li>Every integer is in the <strong>inclusive</strong> range <code>[0, 2<sup>n</sup> - 1]</code>,</li>
	<li>The first integer is <code>0</code>,</li>
	<li>An integer appears <strong>no more than once</strong> in the sequence,</li>
	<li>The binary representation of every pair of <strong>adjacent</strong> integers differs by <strong>exactly one bit</strong>, and</li>
	<li>The binary representation of the <strong>first</strong> and <strong>last</strong> integers differs by <strong>exactly one bit</strong>.</li>
</ul>

<p>Given an integer <code>n</code>, return <em>any valid <strong>n-bit gray code sequence</strong></em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> n = 2
<strong>Output:</strong> [0,1,3,2]
<strong>Explanation:</strong>
The binary representation of [0,1,3,2] is [00,01,11,10].
- 0<u>0</u> and 0<u>1</u> differ by one bit
- <u>0</u>1 and <u>1</u>1 differ by one bit
- 1<u>1</u> and 1<u>0</u> differ by one bit
- <u>1</u>0 and <u>0</u>0 differ by one bit
[0,2,3,1] is also a valid gray code sequence, whose binary representation is [00,10,11,01].
- <u>0</u>0 and <u>1</u>0 differ by one bit
- 1<u>0</u> and 1<u>1</u> differ by one bit
- <u>1</u>1 and <u>0</u>1 differ by one bit
- 0<u>1</u> and 0<u>0</u> differ by one bit
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> n = 1
<strong>Output:</strong> [0,1]
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= n &lt;= 16</code></li>
</ul>

class Solution {
public:
    vector<int> grayCode(int n) {
        vector<string> v_str = solve(n);
        vector<int> v(v_str.size());
        for (int i = 0; i < v_str.size(); i++)
        {
            v[i] = binary_str_to_int(v_str[i]);
        }
        return v;
    }
    vector<int> grayfr(int n)
    {
        if (n <= 0) return {};
        int size = pow(2,n);
        vector<int> v(size);
        for (int i = 0; i < size; i++)
        {
            v[i] = i ^ (i >> 1);
        }
        return v;
    }
private:
    vector<string> solve(int n)
    {
        if (n == 1) return {"0", "1"};
        int p = pow(2,n);
        vector<string> v(p);
        vector<string> v2 = solve(n-1);
        for (int i = 0; i < p; i++)
        {
            if (i < p/2)
            {
                v[i] = v[i] + "0" + v2[i];
            }
            else
            {
                v[i] = v[i] + "1" + v2[p-i-1];
            }
        }
        return v;
    }
    int binary_str_to_int(string s)
    {
        int res = 0;
        for(int i = s.size()-1; i>=0; i--)
        {
            res += (s[i]-'0') * pow(2,s.size()-i-1);
        }
        return res;
    }
};
28378