给定两个整数N和S,所述任务是从区间[0,2(N – 1)]发现数字的圆形排列,与S开始,使得任何一对相邻的数字之间的不匹配比特的数量是一个。
例子:
Input: N = 2, S = 3
Output: [3, 2, 0, 1]
Explanation:
The binary representation of numbers 3, 2, 0 and 1 are “11”, “10”, “01” and “00” respectively.
Therefore, arranging them in the order [3, 2, 0, 1] ensures that the number of bit differences between each pair of adjacent elements (circular) is 1.
Input: N = 3, S = 2
Output: [2, 6, 7, 5, 4, 0, 1, 3]
方法:可以根据以下观察结果解决给定问题:
- A simple observation is that the numbers in the range [2i, 2i + 1 – 1] can be obtained in their natural order by placing ‘1’s before each number in the range [0, 2i – 1].
- Therefore, the problem can be solved recursively by adding ‘1’ before each number before 2i – 1th index and reverse it before appending the new numbers to permutation.
请按照以下步骤解决问题:
- 初始化一个列表,例如res ,以存储所需的排列。
- 初始化一个整数,例如index ,以存储S在从0开始的置换中的位置。
- 在[0,N – 1]范围内进行迭代,并以相反的顺序遍历数组res []并检查当前数字和2 i的和是否为S。如果发现是真的,则使用res的当前索引更新index ,并将当前数字+ 2 i追加到res列表中。
- 按索引位置旋转列表res []。
- 完成上述步骤后,打印列表res []作为答案。
下面是上述方法的实现:
C++
Java
Python3
C#
输出:
时间复杂度: O(N 2 )
辅助空间: O(N)