Input: n =2, start =3Output: [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]
A circular permutation where each adjacent number differs by one bit is exactly a Gray code sequence. By generating the standard Gray code and rotating it so that it starts with start, we get the required permutation.
classSolution {
public: vector<int> circularPermutation(int n, int start) {
int sz =1<< n;
vector<int> g(sz);
for (int i =0; i < sz; ++i) g[i] = i ^ (i >>1);
auto it = find(g.begin(), g.end(), start);
rotate(g.begin(), it, g.end());
return g;
}
};
classSolution {
public List<Integer>circularPermutation(int n, int start) {
int sz = 1 << n;
List<Integer> g =new ArrayList<>();
for (int i = 0; i < sz; i++) g.add(i ^ (i >> 1));
int idx = g.indexOf(start);
List<Integer> ans =new ArrayList<>();
for (int i = 0; i < sz; i++) ans.add(g.get((idx + i) % sz));
return ans;
}
}
1
2
3
4
5
6
7
8
classSolution {
funcircularPermutation(n: Int, start: Int): List<Int> {
val sz = 1 shl n
val g = List(sz) { it xor (it shr 1) }
val idx = g.indexOf(start)
return List(sz) { g[(idx + it) % sz] }
}
}
1
2
3
4
5
6
classSolution:
defcircularPermutation(self, n: int, start: int) -> list[int]:
sz =1<< n
g = [i ^ (i >>1) for i in range(sz)]
idx = g.index(start)
return g[idx:] + g[:idx]
1
2
3
4
5
6
7
8
impl Solution {
pubfncircular_permutation(n: i32, start: i32) -> Vec<i32> {
let sz =1<< n;
letmut g: Vec<i32>= (0..sz).map(|i| i ^ (i >>1)).collect();
let idx = g.iter().position(|&x| x == start).unwrap();
g[idx..].iter().chain(g[..idx].iter()).cloned().collect()
}
}