给出一个函数来输出一个字符串的所有排列。

来源:互联网 发布:顶级域名的含义 编辑:程序博客网 时间:2024/05/08 20:11

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <iostream>
#include <vector>
using namespace std;

char *p = "abcde";
vector<int> st;

/**找index以后的、没有在st中的数。
  *如果不存在则返回-1
  */
int nextVal(int index)
{
  int len = strlen(p);
  vector<int>::iterator it;
  for(int i = (index + 1); i < len; i++ )
  { 
    for(it = st.begin(); it < st.end(); it++)
    {
      if(p[*(it)] == p[i]) break;
    }
   if(it >= st.end())
   {
     return i;
   }
  }
 return -1;
}

/**
  *z在屏幕上输出vector st的内容
  */
void printVector()
{
  vector<int>::iterator it;
  for(it = st.begin(); it < st.end(); it++)
  {
    cout <<*it << " ";
  }
  cout << endl;
}

/**
  *输出p字符串中的字符的排列
  */
void arrange(char *p)
{
  assert(p != NULL);
  int len = strlen(p);
  int val;
  int ret;
  int temp;
  int temp2;
  int count = 0;
  while(true)
  {
    temp = (len - st.size());
    for(int i = 0; i < temp; i++)
    {
      temp2 = nextVal(-1);
      st.push_back(temp2);
 
    }//end of for

    printVector();
    cout << "the count is" << ++count << endl;

    while(st.size() != 0)
    {
      val = *(st.end()-1);
      st.pop_back();
      ret = nextVal(val);
      if(ret != -1)
       {
         st.push_back(ret);
         break;
       }
      else
      {
      }
    }//end of while

  if(st.size() ==0)
  {
    break;
  }
 }//end of while
}//end of arrange

int main()
{
  arrange(p);
  return 1;
}

原创粉丝点击