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

转载至: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);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值