Skip to content

Latest commit

 

History

History
90 lines (68 loc) · 2.54 KB

1238-circular-permutation-in-binary-representation.md

File metadata and controls

90 lines (68 loc) · 2.54 KB

1238. Circular Permutation in Binary Representation - 循环码排列

给你两个整数 nstart。你的任务是返回任意 (0,1,2,,...,2^n-1) 的排列 p,并且满足:

  • p[0] = start
  • p[i]p[i+1] 的二进制表示形式只有一位不同
  • p[0]p[2^n -1] 的二进制表示形式也只有一位不同

 

示例 1:

输入:n = 2, start = 3
输出:[3,2,0,1]
解释:这个排列的二进制表示是 (11,10,00,01)
     所有的相邻元素都有一位是不同的,另一个有效的排列是 [3,1,0,2]

示例 2:

输出:n = 3, start = 2
输出:[2,6,7,5,4,0,1,3]
解释:这个排列的二进制表示是 (010,110,111,101,100,000,001,011)

 

提示:

  • 1 <= n <= 16
  • 0 <= start < 2^n

题目标签:Math

题目链接:LeetCode / LeetCode中国

题解

Language Runtime Memory
cpp 412 ms 119 MB
class Solution {
public:
    void dfs(unordered_set<int>& s, int cur, int n, vector<int>& ret) {
        if (ret.size() == (1 << n)) {
            return;
        }
        for (int i = 0; i < n; i++) {
            if (((cur >> i) & 1) == 0) {
                int r = cur | (1 << i);
                if (s.find(r) == s.end()) {
                    ret.push_back(r);
                    s.insert(r);
                    dfs(s, r, n, ret);
                }
            } else {
                int r = cur & (~(1 << i));
                if (s.find(r) == s.end()) {
                    ret.push_back(r);
                    s.insert(r);
                    dfs(s, r, n, ret);
                }
            }
        }
    }

    vector<int> circularPermutation(int n, int start) {
        vector<int> res;
        unordered_set<int> s;
        res.push_back(start);
        s.insert(start);
        dfs(s, start, n, res);
        return res;
    }
};