zoukankan      html  css  js  c++  java
  • LeetCode GrayCode

    class Solution {
    public:
        vector<int> grayCode(int n) {
            vector<int> res;
            res.push_back(0);
    
            long pow2 = 1;
            for (int i=1; i <= n; i++) {
                int old_len = res.size();
                for (int i=0; i<old_len; i++) {
                    res.push_back(pow2 + res[old_len - i - 1]);
                }
                pow2<<=1;
            }
            return res;
        }   
    };

    再水一发, 不过n==0时,觉得应该返回一个空的vector

    简化版:

    class Solution {
    public:
        vector<int> grayCode(int n) {
            vector<int> res;
            res.push_back(0);
    
            for (int i=0; i<n; i++) {
                int idx = res.size() - 1;
                while (idx >= 0) {
                    res.push_back(res[idx--] | 1<<i);
                }
            }
            
            return res;
        }
    };

    递归方法:

    class Solution {
    public:
        vector<int> grayCode(int n) {
            vector<int> res;
            if (n < 1) {
                res.push_back(0);
                return res;
            } else if (n == 1) {
                res.push_back(0);
                res.push_back(1);
                return res;
            }
            vector<int> sub = grayCode(n - 1);
            int len = sub.size();
            for (int i=0; i < len; i++) {
                res.push_back(sub[i]);
            }
            for (int i=len-1; i>=0; i--) {
                res.push_back((1<<(n-1))|sub[i]);
            }
            return res;
        }
    };
  • 相关阅读:
    Mybatis的动态sql以及分页
    Mybatis入门
    使用java代码操作Redis
    Redis安装和基本操作
    idea安装以及使用
    卢卡斯定理 Lucas (p为素数)
    三分/优选法(黄金分割法)求单峰函数极值
    缩点tarjan
    tarjan 求割点
    tarjan
  • 原文地址:https://www.cnblogs.com/lailailai/p/3783919.html
Copyright © 2011-2022 走看看