• 博客园logo
  • 会员
  • 周边
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
村雨sup
自己选的路,跪着也要走完 XD
博客园    首页    新随笔    联系   管理    订阅  订阅
Leetcode 89

回溯写到自闭;不想就删了;

class Solution {
public:
    vector<int> grayCode(int n) {
        vector<vector<int>> res;
        vector<int> add(n,0);
        DFS(res,add,n,0);
        vector<int> realres;
        for(int i=0;i < res.size();i++){
            realres.push_back(func(res[i]));
        }
        return realres;
    }

    int func(vector<int> nums){
        int res = 0;
        int x = 1;
        for(int i=nums.size()-1;i >= 0;i--){
            if(nums[i] == 1){
                res += x;
            }
            x = x*2;
        }
        return res;
    }

    int trans(int a){
        if(a == 0) return 1;
        else return 0;
    }



    void DFS(vector<vector<int>>& res,vector<int> add,int n,int pos){ 
        if(add.size() == pos){
            res.push_back(add);
        }
        else{
            DFS(res,add,n,pos+1); //其实就是递归的顺序不对!改不来
            add[pos] = trans(add[pos]);
            DFS(res,add,n,pos+1);
        }
    }
};

 正解:(数学方法)

// Binary to grey code
class Solution {
public:
    vector<int> grayCode(int n) {
        vector<int> res;
        for (int i = 0; i < pow(2,n); ++i) {
            res.push_back((i >> 1) ^ i);
        }
        return res;
    }
};

 

posted on 2018-11-05 23:20  村雨sup  阅读(170)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3