zoukankan      html  css  js  c++  java
  • 全排列问题

    D的小L

    时间限制:4000 ms  |  内存限制:65535 KB
     
     
    描述
          一天TC的匡匡找ACM的小L玩三国杀,但是这会小L忙着哩,不想和匡匡玩但又怕匡匡生气,这时小L给匡匡出了个题目想难倒匡匡(小L很D吧),有一个数n(0<n<10),写出1到n的全排列,这时匡匡有点囧了,,,聪明的你能帮匡匡解围吗?
     
    输入
    第一行输入一个数N(0<N<10),表示有N组测试数据。后面的N行输入多组输入数据,每组输入数据都是一个整数x(0<x<10)
    输出
    按特定顺序输出所有组合。
    特定顺序:每一个组合中的值从小到大排列,组合之间按字典序排列。
    样例输入
    2
    2
    3
    样例输出
    12
    21
    123
    132
    213
    231
    312
    321

    CODE:

     1 #include <iostream>
     2 #include <algorithm>
     3 using namespace std;
     4 
     5 int array[] = {1, 2, 3, 4,5,6,7,8,9};
     6 
     7 int main()
     8 {
     9 
    10  int t,n;
    11     cin>>t;
    12  while(t--)
    13  {
    14       cin>>n;
    15       sort(array, array +n);
    16      do
    17   {
    18      for(int i = 0; i < n; i++)
    19      {
    20    cout << array[i]; 
    21      }
    22         cout <<endl;
    23 
    24   } while (next_permutation(array, array + n));
    25  } 
    26 
    27  return 0;
    28 }

    这种用STL的算法效率很低,还有一种是用递归实现

     1 #include <iostream>
     2 #include <vector>
     3 #include <string>
     4 using namespace std;
     5 int array[] = {1, 2, 3, 4};
     6 const int iArraySize = sizeof(array)/sizeof(int);
     7 //删除str的第n个字符
     8 void DeleteCharAt(string& str, int n)
     9 {
    10  if (n < 0 || n >= str.length())
    11  {
    12   return;
    13  }
    14  string tmpStr(str.substr(n + 1));
    15  str = str.substr(0, n) + tmpStr;
    16 }
    17 //base 以该字符串作为基础字符串,进行选择性组合。 
    18 //buff 所求字符串的临时结果 
    19 //result 存放所求结果 
    20 void ListAll(string& strBase, string strBuff, vector<string>& result)
    21 {
    22  if (strBase.length() <= 0)
    23  {
    24   result.push_back(strBuff);
    25  }
    26  for(int i = 0; i < strBase.length(); i++)
    27  {
    28   string tmp(strBase);
    29   DeleteCharAt(tmp, i);
    30   ListAll(tmp, strBuff + strBase[i], result);  
    31  }
    32 }
    33 int main(){
    34  int iCnt = 0;
    35  string str = "1324";
    36  vector<string> vResult;
    37  ListAll(str, "", vResult);
    38  //Output the result
    39  for (int i = 0; i < vResult.size(); ++i)
    40  {
    41   cout << vResult[i] << " ";
    42  }
    43  cout << "/n";
    44  cout << "Total number: " << vResult.size() << endl;
    45  return 0;
    46 }
  • 相关阅读:
    STL hash_map使用
    STL的 string 类赋值
    STL map使用详解
    下面我使用vector容器为基础来构成一棵树
    MFC中CString.Format的详细用法
    error LNK2001: 无法解析的外部符号 "public: static class stdext::hash_map
    !!! STL的string类如何实现CString的Format功能 这是一个经典问题,记住
    STL map和STL set(转载)
    为什么提示此错误?RunTime Check Failure #2 Stack around the variable 'tch1'was corrupted.
    STL源码剖析
  • 原文地址:https://www.cnblogs.com/hpuwangjunling/p/2340273.html
Copyright © 2011-2022 走看看