seals 大约2小时前 平静 的说 订做男女式西服,面料、款式可选,价格288-388,QQ:61582459   ☆绛珠草☆ 大约6小时前 高兴 的说 保真★原装★化妆品QQ群71872775长期超市价团购   xiaofanyy 10月10日 平静 的说 我的生活没颜色了。晕了。迷茫了。   小鱼游 10月10日 悲伤 的说 额,突然觉得人生失去了方向~~~~~   fay_meng 10月9日 平静 的说 冒泡下,提高知名度...   zdk6105 10月9日 平静 的说 哈哈,何为缘?聚散皆为缘   一堆泪水 10月9日 郁闷 的说 期待有缘人。。。   小鱼游 10月8日 平静 的说 干了一整天的活,好累哟   水木落 10月8日 平静 的说 9日8点40分,离校后第一次掠过杨凌。。。。。。   逍遥散人 10月6日 平静 的说 终于回杨凌了 心情还是那样没变化 闷了   [查看全部 330 条唧唧歪歪...]


打印

递归求解排列

递归求解排列

文字文字文字

vector<string> generate_permutations(string word)
{
   vector<string> result;
   if (word.length() == 1)
   {
      result.push_back(word);
      return result;
   }
   for (int i = 0; i < word.length(); i++)
   { //求较少字符序列的排列
      string shorter_word = word.substr(0, i)
        + word.substr(i + 1, word.length() - i - 1);
      vector<string> shorter_permutations
        = generate_permutations(shorter_word);
      for (int j = 0; j < shorter_permutations.size(); j ++)
      {
        string longer_word = word + shorter_permutations  [j];
        result.push_back(longer_word);
      }

   }
   return result; //向上递归直至最外层
}

   以上程序在vc6.0下调试通过。由于使用了vctor模板,需头文件vector.使用这段代码求9个以内字符的排列没问题,最多需要几分钟的时间(如果你的cpu很“牛”,那就另当别论了。)
  如果那位有更好的方法,欢迎与我交流。QQ:305351190
   email:shenlan0829@163.com
   参考资料:Computing Concepts with C++ Essentials

TOP

建议你加个递归深度
要不然会把栈挤暴
http://blog.csdn.net/thisisll/ http://spaces.msn.com/thisisll/

TOP

递归思想追求的是用最原始的思维方式解决困难的问题,把烦心
事留给计算机。
  以上程序目的只在阐述递归的方法,楼上所说的问题还有待研究。
  谢谢你的建议!

TOP

递归就是浪费资源,浪费时间
几个循环可以解决的问题,非要把一个函数在栈里压很多次
http://blog.csdn.net/thisisll/ http://spaces.msn.com/thisisll/

TOP