class Solution {
public:
vector<int> countBits(int num) {
if (num == 0){
data.push_back(0);
return data;
}
int level = ceil(log2(num+1));
int count1 = 0; //目前栈中1的个数
int count2 = 0; //目前栈中元素的个数
int count3 = 0; //输出结点的个数
int temp;
while (1){
while (count2 < level-1){
sta.push(0);
count2++;
}
if (count2==level-1){//只有到叶子结点的上一层时才输出
data.push_back(count1); //0入栈
count3++;
if (count3 == num + 1)break;
data.push_back(count1 + 1); //1入栈
count3++;
if (count3 == num + 1)break;
}
temp = sta.top();
while (count2>0&&temp==1){
if (count3 == num + 1){
cout <<"finished!"<< endl;
}
sta.pop();
count2--;
count1--;
if(count2>0)temp = sta.top();
}
if (count2>0&&temp==0){
sta.pop();
sta.push(1);
count1++;
}
}
return data;
}
stack<int>sta;
vector<int>data;
};
/*算法综述:
在这个算法中我们利用如下的树型结构:
start
/ \
/ \
0 1
/ \ / \
0 1 0 1
/ \ / \ /\ /\
0 1 0 1 0 1 0 1
对应的数 0 1 2 3 4 5 6 7
所以利用二叉树的遍历方法就可以求解法。
算法的时间复杂度为O(NlogN)
ps:leetcode上的运行时间为144ms,有点长,算法待改进!
*/