<p>An array <code>nums</code> of length <code>n</code> is <strong>beautiful</strong> if:</p>

<ul>
	<li><code>nums</code> is a permutation of the integers in the range <code>[1, n]</code>.</li>
	<li>For every <code>0 &lt;= i &lt; j &lt; n</code>, there is no index <code>k</code> with <code>i &lt; k &lt; j</code> where <code>2 * nums[k] == nums[i] + nums[j]</code>.</li>
</ul>

<p>Given the integer <code>n</code>, return <em>any <strong>beautiful</strong> array </em><code>nums</code><em> of length </em><code>n</code>. There will be at least one valid answer for the given <code>n</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> n = 4
<strong>Output:</strong> [2,1,4,3]
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> n = 5
<strong>Output:</strong> [3,1,2,5,4]
</pre>
<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

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

class Solution {
public:
    vector<int> f(vector<int> &ans) {
        int n = ans.size();
        if (n <= 1) return ans;  // Base case: if size <= 1, it's already beautiful
        
        // Separate odd and even indexed elements
        vector<int> odd, even;
        
        for (int i = 0; i < n; i += 2) {
            even.push_back(ans[i]);  // Elements at even indices
        }
        
        for (int i = 1; i < n; i += 2) {
            odd.push_back(ans[i]);  // Elements at odd indices
        }
        
        // Recursively apply the function on both parts
        odd = f(odd);
        even = f(even);
        
        // Merge the results
        vector<int> res;
        res.reserve(n);  // Preallocate space for the result vector
        
        // Add the odd and even arrays back into the result
        res.insert(res.end(), odd.begin(), odd.end());   // Insert odd elements first
        res.insert(res.end(), even.begin(), even.end()); // Insert even elements next
        
        return res;
    }

    // Driver function to create a beautiful array
    vector<int> beautifulArray(int n) {
        // Initialize ans with [1, 2, 3, ..., n]
        vector<int> ans(n);
        for (int i = 0; i < n; ++i) {
            ans[i] = i + 1;
        }
        
        // Apply the recursive function
        return f(ans);
    }
};
18200