BackTrack with C++


  • 0
    2

    class Solution {
    public:
    vector<int> grayCode(int n) {
    string str;
    str.append(n,'0');
    vector<int> res;
    res.push_back(0);
    code(res,str,n-1);
    return res;
    }
    void code(vector<int>& res,string str,int k)
    {
    if(k<0) return;
    else
    {
    for(int i=k;i>=0;i--)
    {
    str[i]= str[i]=='0'?'1':'0';
    int temp=strtol(str.c_str(),NULL,2);
    res.push_back(temp);
    code(res,str,i-1);
    str[i]= str[i]=='0'?'1':'0';
    }
    }
    }
    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.