Leetcode 1238 Circular Permutation in Binary Representation 格雷码 gray code

本文介绍了一种基于格雷码的算法,该算法能够生成一个特定的整数排列,其中任意两个相邻元素仅在二进制表示下相差一位。通过使用i^(i>>1)的巧妙计算,我们能够实现循环排列,确保了起始元素与末尾元素也仅相差一位。文章提供了Python代码示例,展示了如何生成这种特殊的排列。

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

 

-------------------------------------------------------

格雷码,需要知道两点:

1. 格雷码对应卡诺图,所以可以循环:

2. 格雷码的计算可以通过i^(i>>1),其实i=range(n),代码为

class Solution:
    def circularPermutation(self, n, start):
        return [start ^ i ^ (i>>1) for i in range(1<<n)]

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值