C ++中二进制表示形式的循环置换
假设我们有2个整数n并开始。我们的任务是返回(0,1,2.....,2^n-1)的任何排列p,如下所示-
p[0]=开始
p[i]和p[i+1]的二进制表示形式仅相差一位。
p[0]和p[2^n-1]的二进制表示形式也必须仅相差一位。
因此,如果输入类似于n=2且start=3,则返回的数组将为[3,2,0,1],即[11,10,00,01]
为了解决这个问题,我们将遵循以下步骤-
ans是一个数组
对于0到2^n的i
将开始XORiXORi/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, ]