-5

可能重复:
打印给定元素排列的程序

所以,我有数字 153,我的程序需要输出 - 135、153、315、351、513、531。换句话说,所有可能的数字。任何想法如何做到这一点?

4

3 回答 3

0

这是一小块足迹,它可以帮助你

#include <stdio.h>

int main(int argc, char** argv){
  int a,b,c;

  for(a=1; a<4; a++){
    for(b=1; b<4; b++){
      for(c=1; c<4; c++){
      if(!(a==b || a==c || b==c))
        printf("%d%d%d\n",a,b,c);
      }
    }
  }

  return 0;
}
于 2012-12-11T17:57:44.740 回答
0

从 int 更改为 string,然后更改为字符数组。然后使用嵌套循环。

于 2012-12-11T17:42:18.923 回答
0
#include<iostream>
#include<vector>

void swap(int& a, int& b)
{ int x=a;
a=b;
b=x;
}

void printVector(std::vector<int>& theVector)
{ for (unsigned int i=0; i<theVector.size(); i++)
std::cout << theVector[i] << ",";
std::cout << "\n";
}

void generateAllPermutations(std::vector<int>& toBePermuted, unsigned int nextIndex)
{ if (nextIndex==toBePermuted.size())
{ printVector(toBePermuted);
return;
}
for (unsigned int i=nextIndex; i<toBePermuted.size(); i++)
{ swap(toBePermuted[i], toBePermuted[nextIndex]);
generateAllPermutations(toBePermuted, nextIndex+1);
swap(toBePermuted[i], toBePermuted[nextIndex]);
}
}

void generateAllPermutations(std::vector<int>& toBePermuted)
{ generateAllPermutations(toBePermuted, 0);
}

int main()
{ std::vector<int> theVector;

theVector.push_back(1);
theVector.push_back(3);
theVector.push_back(5);
generateAllPermutations(theVector);
//note: you will have to print out the vector yourself
}
于 2012-12-11T17:53:36.327 回答