Is that "don't know how to do it on paper" or "I can do it on paper, just not in code".
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
#include <iostream>
#include <string>
#include <vector>
#include <set>
using namespace std;
int main()
{
int n;
cout << "Enter n: "; cin >> n;
vector< set<string> > S( 1 + n );
S[1] = { "1" };
if ( n > 1 ) S[2] = { "11", "2" };
for ( int i = 3; i <= n; i++ )
{
for ( string s : S[i-2] ) S[i].insert( s + "2" );
for ( string s : S[i-1] ) S[i].insert( s + "1" );
}
for ( string s : S[n] ) cout << s << " ";
}
|
Enter n: 6
111111 11112 11121 11211 1122 12111 1212 1221 21111 2112 2121 2211 222 |
This one usually uses less memory:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
#include <iostream>
#include <string>
#include <set>
using namespace std;
int main()
{
set<string> SM2{ "1" }, SM1{ "11", "2" }, S;
int n;
cout << "Enter n: "; cin >> n;
if ( n == 1 )
{
S = SM2;
}
else if ( n == 2 )
{
S = SM1;
}
else
{
for ( int i = 3; i <= n; i++ )
{
S.clear();
for ( string s : SM2 ) S.insert( s + "2" );
for ( string s : SM1 ) S.insert( s + "1" );
SM2 = SM1;
SM1 = S;
}
}
for ( string s : S ) cout << s << " ";
}
|
Last edited on