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]
andp[i+1]
differ by only one bit in their binary representation.p[0]
andp[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
思路:一看就是格雷码
Gray code is a binary numeral system where two successive values differ in only one bit.
For example, the sequence of Gray codes for 3-bit numbers is: 000, 001, 011, 010, 110, 111, 101, 100, so G(4)=6.
下一位格雷码的计算方式:然后从后往前看,看下更新这位后得到的新数字是否在之前出现过,如果有就一直往前看,
比如起始是000,
把最后一位改掉得到001,没有出现过
然后接下来,001吧最后因为改掉成为000,出现过,所以吧001第二位改掉变成011,没出现过,所以下一个是011
以此类推,然后你可以发现G(n)=n^(n>>1),比如第4位格雷码对应的是4^2=6
然后题目的意思其实就是找一个格雷码序列,然后有个start的offset而已
class Solution(object):
def circularPermutation(self, n, start):
"""
:type n: int
:type start: int
:rtype: List[int]
"""
res = []
for i in range(1<<n):
res.append(start^(i^(i>>1)))
return res
s=Solution()
print(s.circularPermutation(2,3))