JAVA|JAVA 实现全排列和组合

参考了这篇文章
https://blog.csdn.net/leixingbang1989/article/details/47761171
代码:

import java.util.LinkedList; import java.util.List; import java.util.Scanner; public class Main {public static void arrange(String s, List list) { if (list.size() == 0) { System.out.println(s); } else { for (int i = 0; i < list.size(); ++i) { List temp = new LinkedList<>(list); //取出一个数,剩下的数进行全排列 Integer remove = temp.remove(i); arrange(s + remove, temp); temp = null; } } }public static void group(String s, List list, int n) { if (n == 0) { System.out.println(s); } else { for (int i = 0; i < list.size(); ++i) { Integer integer = list.get(i); int length = s.length(); //限定前面的数比后面的小,用来去重复,例如 1 2 和2 1 if(length != 0 && s.charAt(length - 1) > integer + '0'){ continue; } List temp = new LinkedList<>(list); Integer remove = temp.remove(i); group(s + remove, temp, n - 1); temp = null; } } }public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); List list = new LinkedList<>(); for (int i = 1; i <= n; ++i) { list.add(i); } arrange("", list); System.out.println(); group("", list, 2); System.out.println(); } }

【JAVA|JAVA 实现全排列和组合】2018/3/28补充
不用每次都新建一个list,只需要将之前remove掉的值交换,换到前面即可
public static void swap(List list, int i, int j){ Integer src = https://www.it610.com/article/list.get(i); Integer dst = list.get(j); Integer temp = src; src = dst; dst = temp; }public static void arrange2(String s, List list, int start) { if (start == list.size()) { System.out.println(s); } else { for (int i = start; i < list.size(); ++i) { swap(list, start, i); arrange2(s + list.get(start), list, start + 1); swap(list, start, i); } } }

可以参考https://blog.csdn.net/qq_34115899/article/details/79733654
然而,上面这段代码是错误的
错误的
错误的
错误的
因为这样根本没办法交换list里面的2个值
原因请看
解决方法,可以用list的set方法,也可以改成int数组

    推荐阅读