题目
给定正整数n, 输出外观数列的第n项
结果:
input a num: 4
res: 1211
input a num: 5
res: 111221
input a num: 6
res: 312211
input a num: 1
res: 1
input a num: 2
res: 11
input a num: 3
res: 21
input a num: 4
res: 1211
input a num: 5
res: 111221
代码
事实证明,做题目不要过分考虑内存问题,下面为了避免内存动态分配,搞了两个缓冲区交互来解决,但实际都致不少问题。但实际项目中,必须认真考虑。
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
class CountAndSayTool {
public:
CountAndSayTool() {
cur_lst = new int[MAX_COUNT];
next_lst = new int[MAX_COUNT];
}
~CountAndSayTool() {
delete[] cur_lst;
delete[] next_lst;
}
void _CountAndSay(int* num_lst, const int lst_count, const int cur_n, const int target_n, std::string& res) {
if (target_n == cur_n) {
std::stringstream strstr;
for (int i = 0; i < lst_count; ++i) {
strstr << num_lst[i];
}
res = strstr.str();
return;
}
int* next_num_lst = nullptr;
int next_count = 0;
if (lst_count == 0||num_lst ==NULL) {
next_num_lst = next_lst;
next_num_lst[0] = 1;
next_count = 1;
}else {
//auto nit = num_lst.begin();
int cur_index = 0;
int cur_num = num_lst[0];
int num_count = 1;
++cur_index;
int next_index = 0;
next_num_lst = this->next_lst;
for (; cur_index < lst_count; ++cur_index) {
if (cur_num == num_lst[cur_index]) {
num_count++;
}else {
if (next_index + 1 < MAX_COUNT) {
next_num_lst[next_index] = num_count;
++next_index;
next_num_lst[next_index] = cur_num;
++next_index;
cur_num = num_lst[cur_index];
num_count = 1;
}else {
break;
}
}
}
if (next_index + 1 < MAX_COUNT) {
next_num_lst[next_index] = num_count;
++next_index;
next_num_lst[next_index] = cur_num;
++next_index;
cur_num = num_lst[cur_index];
num_count = 1;
}
next_count = next_index;
}
int* t = this->cur_lst;
this->cur_lst = next_lst;
this->next_lst = t;
_CountAndSay(next_num_lst, next_count, cur_n + 1, target_n, res);
}
static const int MAX_COUNT = 30 * 2;
private:
int* cur_lst;
int* next_lst;
};
void CountAndSay() {
CountAndSayTool tool;
std::string res;
int n = 1;
while (n > 0) {
std::cout << "input a num: ";
std::cin >> n;
tool._CountAndSay(NULL, 0, 0, n, res);
std::cout << "res: " << res << std::endl;
}
}