在 C++ 中迴圈二進位制表示中的排列
假設我們有 2 個整數 n 和 start。我們的任務是返回 (0,1,2.....,2^n -1) 的任意排列 p 如下所示 −
- p[0] = start
- p[i] 和 p[i+1] 在其二進位制表示中僅有一位不同。
- p[0] 和 p[2^n -1] 在其二進位制表示中也必須僅有一位不同。
因此,如果輸入類似 n = 2 和 start = 3,則返回的陣列將是 [3,2,0,1],它們是 [11,10,00,01]
為了解決這個問題,我們將遵循以下步驟 −
- ans 是一個數組
- 對於 i 介於 0 和 2^n 之間的範圍
- 將 start XOR i XOR i/2 插入到 ans 中
- 返回 ans
讓我們看下面的實現以獲得更好的理解 −
示例
#include <bits/stdc++.h> using namespace std; void print_vector(vector<auto> v){ cout << "["; for(int i = 0; i<v.size(); i++){ cout << v[i] << ", "; } cout << "]"<<endl; } class Solution { public: vector<int> circularPermutation(int n, int start) { vector <int> ans; for(int i = 0 ; i < 1<<n; i++){ ans.push_back(start ^ i ^(i>>1)); } return ans; } }; main(){ Solution ob; print_vector(ob.circularPermutation(5,3)); }
輸入
5 3
輸出
[3, 2, 0, 1, 5, 4, 6, 7, 15, 14, 12, 13, 9, 8, 10, 11, 27, 26, 24, 25, 29, 28, 30, 31, 23, 22, 20, 21, 17, 16, 18, 19, ]
廣告