c++递归生成格雷码

首先分析,三位的格雷码是在二位的基础上生成的
n位是在n-1的基础上生成的,具体生成规律在于,再n-1位前面补0, 在前面补1再倒序;

class GrayCode {
    
    
public:
    
    vector<string> getGray(int n) {
    
    
        // write code here
        vector<string> now;
     //递归终止条件及返回
       if(n==0) return now;
        if(n==1) {
    
    
            now.push_back("0");
            now.push_back("1");
            return now;
        }
        //单层递归逻辑
        vector<string> old = getGray(n-1);
  
        for(int i = 0;i<pow(2, n-1);i++){
    
    
            now.push_back("0"+old[i]);
        }
        for(int i = 0;i<pow(2, n-1);i++){
    
    
            now.push_back("1" + old[old.size()-1-i]);
        }
      return now;  
    }
};

猜你喜欢

转载自blog.csdn.net/PETERPARKERRR/article/details/124042724