我想出了如何使用递归生成集合的排列,但是我无法弄清楚如何保存它产生的值。有没有办法重新扫描程序输出的数据以保存它?或者我在这里走错了方向?
以下是我一直在使用的代码:
import java.util.Scanner;
import java.util.Arrays;
public class test
{
//Arrays.toString(int[]); >>Converts int array to string.
//int foo = Integer.parseInt("1234");
public static void main()
{
String str;
str = getStr();
//
int n = str.length();
//Trying to use this to catch output!!
int nf = 1;
for(int i=n;i>0;i--)
{nf *= i;}
int[][] array = new int[nf][n];
//
char[] arr = str.toCharArray();
boolean[] visited = new boolean[n];
for(int i=0;i<n;i++)
{visited[i] = false;}
char[] branch = new char[n];
generatePermutations(arr,n,branch,-1,visited);
//The visited array keeps track of which nodes have been visited already.
}
public static void generatePermutations(char[] arr,int size,char[] branch,int level,boolean[] visited)
{
if(level >= size-1)
{System.out.println(branch);
return;
}
for(int i=0;i<size;i++)
{
if(!visited[i])
{
branch[++level] = arr[i];
visited[i] = true;
generatePermutations(arr,size,branch,level,visited);
visited[i] = false;
level--;
}
}
}
//
public static String getStr()
{
Scanner kb = new Scanner(System.in);
String str;
int n;
System.out.print("Enter the size (n): ");
n = kb.nextInt();
int[] initialSet = new int[n];
for(int i=0;i<n;i++)
{
initialSet[i] = (i+1);
}
str = Arrays.toString(initialSet).replace(", ", "").replace("[","").replace("]","");
return str;
}
}