如何求n个元素的全排列,如1 2 3的全排列为 1 2 3 ; 1 3 2 ; 2 1 3; 2 3 1; 3 1 2 ; 3 2 1;
使用的是递归,暴力搜索所有可行的方案。可以用一个一维数组存储每次找到的一种方案。
// 输出一个n,输出1~n的全排列
import java.util.*;
public class Main{
static int N = 10;
static int n ;
static int path[] = new int[N]; //存储一种可行的方案
static boolean st[] = new boolean[N]; //判断是否被用过 true为被用过 flase为没有
static void dfs(int u){
if(u == n){ // 从第u = 0个位置开始找,当u == n 时一种方案找到完毕输出
for(int i = 0;i
运行效果
上述求1~n的全排列,可以扩展为求一个数组的全排列
二、求n个元素的全排列
只需要将上述的dfs方法内的 path[u] = i; 改成输入的元素就行path[u] = nums[i];
代码示例
求输入的n个数的全排列
import java.util.*;
public class Main{
static int N = 10;
static int n ;
static int path[] = new int[N]; //存储一种可行的方案
static boolean st[] = new boolean[N]; //判断是否被用过 true为被用过 flase为没有
static int nums[] = new int[N]; //用来存储输入的n个元素
static void dfs(int u){
if(u == n){ // 从第u = 0个位置开始找,当u == n 时一种方案找到完毕输出
for(int i = 0;i
运行效果



