1234,四个不同的数字组成多少种不同的数
java语言
public class Quanpailie {
static int t=0;//来记录多少不同的数
public static void swap(int a[] ,int n,int m){//前后交换
int temp=a[m];
a[m]=a[n];
a[n]=temp;
}
public static void perm(int[] a, int begin, int end) {
if (begin == end) {
for (int i = 0; i <= end; i++) {
System.out.print(a[i]);
}
System.out.println();
t++;
return;
}else
for(int j=begin;j<=end;j++){
swap(a, begin, j);
perm(a, begin+1, end);
swap(a, begin, j);
}
}
public static void main(String[] args) {
int[] a={1,2,3,4};
perm(a, 0, a.length-1);
System.out.println("共有"+t+"中排列方式");
}
}
1234,四个不同的数字组成多少种不同的数
java语言
public class Quanpailie {
static int t=0;//来记录多少不同的数
public static void swap(int a[] ,int n,int m){//前后交换
int temp=a[m];
a[m]=a[n];
a[n]=temp;
}
public static void perm(int[] a, int begin, int end) {
if (begin == end) {
for (int i = 0; i <= end; i++) {
System.out.print(a[i]);
}
System.out.println();
t++;
return;
}else
for(int j=begin;j<=end;j++){
swap(a, begin, j);
perm(a, begin+1, end);
swap(a, begin, j);
}
}
public static void main(String[] args) {
int[] a={1,2,3,4};
perm(a, 0, a.length-1);
System.out.println("共有"+t+"中排列方式");
}
}
结果:
C++语言解决
// Pailie.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
int t = 0;
int a[4] = { 1, 2, 3, 4 };
void swap(int n, int m);
void perm(int begin, int end);
int main()
{
perm(0,3);
cout <<"共有"<< t <<"种不同的数"<< endl;
system("pause");
return 0;
}
void swap(int n, int m){
int temp;
temp = a[m];
a[m] = a[n];
a[n] = temp;
}
void perm(int begin, int end){
if (begin == end){
for (int i = 0; i <= end; i++){
cout << a[i];
}
cout << "\n";
t++;
return;
}
else
{
for (int i = begin; i <=end; i++)
{
swap(begin,i);
perm(begin + 1, end);
swap(begin, i);
}
}
}
结果: