您的位置:首页 > 其它

输入一个n,输出结果1 2 3---经典算法

2009-07-07 14:29 309 查看
转载至:http://blog.chinaunix.net/u/33061/showart_266703.html

输入一个n,输出结果分别用1、2、3输出,即输出n长度1 2 3的所有组合。

如n=1,输出1 2 3 ,n=2,输出 11 12 13 21 22 23 31 32 33
 
#include <iostream>

#include <stack>

#include <vector>

#include <tchar.h>

#include<math.h>
using std::vector;

using std::stack;

using std::cout;

using std::endl;

using std::cin;
 
void printThree(int n,int len);

//输入n,打印出1---n的三进制,三进制各位分别加1输出

//len是输出的三进制的长度
void printAll(int n);

//输入一个n,输出结果

//分别用1、2、3输出,输入一个n,输出n长度1 2 3的所有组合。

//如n=1,输出1 2 3 ,n=2,输出 11 12 13 21 22 23 31 32 33

int _tmain(int argc, _TCHAR* argv[])

{

 int n;

 cout<<"input a integer"<<endl;

 cin>>n;

 printAll(n);//output the result;

 cout<<endl;

 return 0;

}
void printThree(int n,int len)

{

 //输入n,打印出n的三进制,三进制各位分别加1输出

//len是输出的三进制的长度

 int count=0;//记忆三进制的年度(?)

 stack<int> intstack;//define a stack
 while(n)

 {//打出三进制 各位加1

  intstack.push(n%3+1);

  n/=3;

  count++;

 }

 while(count<len)

 {//输出len 位

  intstack.push(1);

   count++;

 }

 while(!intstack.empty())

 {

  cout<<intstack.top();

  intstack.pop();

 }

  cout<<"   ";

}
void printAll(int n)

{

 //分别用1、2、3输出,即输出n长度1 2 3的所有组合。

//如n=1,输出1 2 3 ,n=2,输出 11 12 1321 22 23 31 32 33

 

 for(vector<int>::size_type i=0;i<pow(3,n);i++)

  printThree(i,n);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法
相关文章推荐