Java 实现排列、组合、组合后排列!从m个里面选n个问题!今晚笔试同程旅游,最后一个编程题:关于排列组合的,原题的意思是:由 1,2,3,4这四个数字中选出3个数字,然后这些数最后能组合成多少个数?
问题一
由 1,2,3,4这四个数字中选出3个数字,然后这些数最后能组合成多少个数?
先上代码:
public class Main
{
public static final int n = 3;
public static int m = 4;
/**
* @param args
*/
public static void main(String[] args)
{
int[] array = new int[n];
f(array, 0);
}
public static void f(int[] array, int now)
{
if (now >= n)
{
for (int i : array)
{
System.out.print(i + " ");
}
System.out.println();
return;
}
else
{
for (int start = 1; start <= m; start++)
{
array[now] = start;
if (j(array, now))// 判断是否出现重复
{
f(array, now + 1);
}
}
}
}
public static boolean j(int[] array, int now)
{
for (int i = 0; i <= now; i++)
{
for (int j = i + 1; j <= now; j++)
{
if (array[i] == array[j])
{
return false;
}
}
}
return true;
}
}
结果是
一共24个程序运行结果如下:
1 2 3
1 2 4
1 3 2
1 3 4
1 4 2
1 4 3
2 1 3
2 1 4
2 3 1
2 3 4
2 4 1
2 4 3
3 1 2
3 1 4
3 2 1
3 2 4
3 4 1
3 4 2
4 1 2
4 1 3
4 2 1
4 2 3
4 3 1
4 3 2
问题二(排列问题)
那么问题来了,我只想要对4个数全排列,我该怎么做呢?只要对n的值做修改就OK了,是不是很简单?
public class Main
{
public static final int n = 4;//改这个地方
public static int m = 4;
/**
* @param args
*/
public static void main(String[] args)
{
int[] array = new int[n];
f(array, 0);
}
public static void f(int[] array, int now)
{
if (now >= n)
{
for (int i : array)
{
System.out.print(i + " ");
}
System.out.println();
return;
}
else
{
for (int start = 1; start <= m; start++)
{
array[now] = start;
if (j(array, now))// 判断是否出现重复
{
f(array, now + 1);
}
}
}
}
public static boolean j(int[] array, int now)
{
for (int i = 0; i <= now; i++)
{
for (int j = i + 1; j <= now; j++)
{
if (array[i] == array[j])
{
return false;
}
}
}
return true;
}
}
问题三(组合问题)
那么问题又来了?如果我们只是想单纯的从4个数字中选3个数字,怎么来实现呢?废话不多说:见下面代码,下面的代码是基于上面加工而成,所以简洁明了!
public class Main
{
public static final int n = 3;
public static int m = 4;
/**
* @param args
*/
public static void main(String[] args)
{
int[] array = new int[n];
f(array, 0, 1);
}
public static void f(int[] array, int now, int start)
{
if (now >= n)
{
for (int i : array)
{
System.out.print(i + " ");
}
System.out.println();
return;
}
else
{
for (; start <= m; start++)
{
array[now] = start;
if (j(array, now))
{
f(array, now + 1, start + 1);
}
}
}
}
public static boolean j(int[] array, int now)
{
for (int i = 0; i <= now; i++)
{
for (int j = i + 1; j <= now; j++)
{
if (array[i] == array[j])
{
return false;
}
}
}
return true;
}
}
程序输出结果如下:
1 2 3
1 2 4
1 3 4
2 3 4
总结:排列组合问题往往是穷举法的一种体现形式,所以,还是要掌握好的!