1238. Circular Permutation in Binary Representation
- Circular Permutation in Binary Representation python solution
题目描述
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.

解析
按照题目的要求,生成的码字序列就是格雷码。
而格雷码自身生成的公式为i^(i>>1),自身和右移一位的自己做异或。
但是本体还有一个限定,就是开始的给定了格雷码序列的开始。start=start^0=start
1<<n就相当于2的n次幂!!!!!!!!
// An highlighted block
class Solution:
def circularPermutation(self, n, start):
return [start ^ i ^ i >> 1 for i in range(1 << n)]
Reference
https://leetcode.com/problems/circular-permutation-in-binary-representation/discuss/414203/JavaC%2B%2BPython-4-line-Gray-Code
本文探讨了如何根据给定的整数n和起始值,生成一个满足特定条件的循环排列序列。序列中任意两个相邻元素仅在二进制表示下相差一位,并且首尾元素也满足这一条件。解决方案基于格雷码的生成原理,通过异或操作实现了从起始值到目标序列的转换。
417

被折叠的 条评论
为什么被折叠?



