public class Solution {
//如果n = 5(即题中的MAX为5),那么应该有60种情况
public static void main(String[] args) throws Exception {
initData();
Lexi2(list);
int count=0;
for (int i = 0; i < allList.size(); i ++) {
count++;
for (int j = 0; j < list.size(); j ++) {
System.out.print(allList.get(i).get(j) + " ");
}
System.out.println("");
}
System.out.println(count);
}
private static final int MAX = 3;
private static List<Integer> list = new ArrayList<>();
private static List<List<Integer>> allList = new ArrayList<>();
private static void initData() {
for (int i = 1; i <= MAX; i ++) {
list.add(i);
}
allList.add(list);
}
//这里是递归形式,传进来的必须是增序的
private static void Lexi(List<Integer> list) {
int size = list.size();
//从右往左,找出第一组 左小于右 的数
//现在 1 2 3 4 5
int a = -1;
for (int i = size - 1; i >= 1; i --) {
if (list.get(i - 1) < list.get(i)) {
a = i - 1;
break;
}
}
if (a == -1) {//执行完了退出递归
return;
}
int b = 0;
for (int i = size - 1; i > a; i --) {
if (list.get(a) < list.get(i)) {
b = i;
break;
}
}
List<Integer> newList = new ArrayList<>();
newList.addAll(list);
Collections.swap(newList, a, b);
//排序,从a + 1到最后都排一次序
sort(newList, a + 1, size - 1);
allList.add(newList);
Lexi(newList);
}
//这里采用的是非递归形式,传进来的必须是增序的
private static void Lexi2(List<Integer> list) {
List<Integer> mList = new ArrayList<>();
mList.addAll(list);
int size = mList .size();
//计算需要几次循环:其实就是你将会得到几个数
int num = 1;
for (int i = 1; i <= size; i ++) {
num *= i;
}
while ((-- num) != 0) {
int a = 0;
for (int i = size - 1; i >= 1; i --) {//最后一个数-第二个数
if (mList .get(i - 1) < mList .get(i)) {
a = i - 1;
break;
}
}
int b = 0;
for (int i = size - 1; i > a; i --) {
if (mList .get(i) > mList .get(a)) {
b = i;
break;
}
}
Collections.swap(mList, a, b);
sort(mList, a + 1, size - 1);
List<Integer> newList = new ArrayList<>();
newList.addAll(mList);
allList.add(newList);
}
}
//升序排序
private static void sort(List<Integer> list, int start, int end) {//1 2
if (start == end) {
return;
} else {
for (int i = start; i <= end; i ++) {
int min = Integer.MAX_VALUE;
int index = -1;
for (int j = i; j <= end; j ++) {
if (list.get(j) < min) {
min = list.get(j);
index = j;
}
}
Collections.swap(list, i, index);
}
}
}
}
排列组合方式
最新推荐文章于 2024-08-23 15:54:50 发布