# 1238. Circular Permutation in Binary Representation

Given 2 integers n and start. Your task is return any permutation p of (0,1,2.....,2^n -1) such that :

• p[0] = start
• p[i] and p[i+1] differ by only one bit in their binary representation.
• p[0] and p[2^n -1] must also differ by only one bit in their binary representation.

Example 1:

Input: n = 2, start = 3
Output: [3,2,0,1]
Explanation: The binary representation of the permutation is (11,10,00,01).
All the adjacent element differ by one bit. Another valid permutation is [3,1,0,2]

Example 2:

Input: n = 3, start = 2
Output: [2,6,7,5,4,0,1,3]
Explanation: The binary representation of the permutation is (010,110,111,101,100,000,001,011).

Constraints:

• 1 <= n <= 16
• 0 <= start < 2 ^ n

Int Binary Gray Code ^011
0 000 000 011
1 001 001 010
2 010 011 000
3 011 010 001
4 100 110 101
5 101 111 100
6 110 101 110
7 111 100 111

class Solution {
public:
vector<int> circularPermutation(int n, int start) {
vector<int> res;
for (int i = 0; i < (1 << n); ++i) {
res.push_back(start ^ i ^ (i >> 1));
}
return res;
}
};

class Solution {
public:
vector<int> circularPermutation(int n, int start) {
vector<int> res;
for (int i = 0; i < (1 << n); ++i) {
res.push_back(i ^ (i >> 1));
}
rotate(res.begin(), find(res.begin(), res.end(), start), res.end());
return res;
}
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1238

Gray Code

https://leetcode.com/problems/circular-permutation-in-binary-representation/

https://leetcode.com/problems/circular-permutation-in-binary-representation/discuss/469592/C%2B%2B-6-line-intuitive-DP-solution

https://leetcode.com/problems/circular-permutation-in-binary-representation/discuss/414203/JavaC%2B%2BPython-4-line-Gray-Code

LeetCode All in One 题目讲解汇总(持续更新中…)

|

Venmo 打赏

—|—

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation