C - 找到所有不同的数字

时间:2012-12-11 17:39:35

标签: c arrays numbers

  

可能重复:
  Program to print permutations of given elements

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

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分: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
}

答案 2 :(得分: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;
}