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]
andp[i+1]
differ by only one bit in their binary representation.p[0]
andp[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
Solution 1: Gray Code (DP) + Rotation
Gray code starts with 0, need to rotate after generating the list.
Time complexity: O(2^n)
Space complexity: O(2^n)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// Author: Huahua class Solution { public: vector<int> circularPermutation(int n, int start) { vector<vector<int>> dp(n + 1); dp[0] = {0}; for (int i = 1; i <= n; ++i) { dp[i] = dp[i - 1]; for (int j = dp[i - 1].size() - 1; j >= 0; --j) dp[i].push_back(dp[i - 1][j] | (1 << (i - 1))); } for (auto it = begin(dp[n]); it != end(dp[n]); ++it) if (*it == start) { rotate(begin(dp[n]), it, end(dp[n])); break; } return dp[n]; } }; |
Solution 2: Gray code with a start
Time complexity: O(2^n)
Space complexity: O(1)
C++
1 2 3 4 5 6 7 8 9 10 |
// Author: Huahua class Solution { public: vector<int> circularPermutation(int n, int start) { vector<int> ans(1 << n); for (int i = 0; i < 1 << n; ++i) ans[i] = start ^ i ^ i >> 1; return ans; } }; |