一、Problem
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.
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]
Constraints:
1 <= n <= 16
0 <= start < 2 ^ n
二、Solution
方法一:回溯
這裏要想到如何獲得一個和上一個數字的二進制位只有一位不同的數字:int v = cur ^ (1 << j) (0 < j <n)
class Solution {
List<Integer> ans;
int tot, n;
boolean fl, vis[];
void dfs(int i, int cur) {
if (i == tot) {
fl = true;
return;
}
if (fl)
return;
ans.add(cur);
vis[cur] = true;
for (int j = 0; j < n; j++) { // 從低位到高位進行翻轉,但本題沒有順序要求
int v = cur ^ (1 << j);
if (!vis[v])
dfs(i+1, v);
}
}
public List<Integer> circularPermutation(int n, int start) {
tot = 1 << n;
this.n = n;
vis = new boolean[tot+1];
ans = new LinkedList<>();
dfs(0, start);
return ans;
}
}
遞歸和迭代的寫法思路是一樣的:
for (int i = 1; i < tot; i++)
for (int j = 0; j < n; j++) {
...
}
複雜度分析
- 時間複雜度:,
- 空間複雜度:,
方法二:格雷碼 + 旋轉數組(代辦)
參考了別人的思路,在這之前還不知道格雷碼
複雜度分析
- 時間複雜度:,
- 空間複雜度:,