嗨我需要一个排列的java progaram和两个输入的组合,一个字符串和一个整数。
Ex: - 如果我们将字符串作为" abcd"并给出第二个输入为2然后输出应该是{ab,ac,ad,ba,bc,bd,ca,cb,cd,da,db,dc}如果我们给第二个输入为3然后组合应该像{abc ,abd,bad,bcd,cab,cbd .........}
这是我试过的
package aaa;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.Scanner;
public class Main {
public static void main (String args[])
{
System.out.println("Please enter the string whose permutations we need to show ");
Scanner in = new Scanner(System.in);
String original=in.nextLine();
System.out.println("enter number");
int n=in.nextInt();
System.out.println("Results are :");
for (int i = 0; i < n; i++) {
permute1(original,n);
}
}
public static void permute1( String input, int x)
{
StringBuffer outputString = new StringBuffer();
String input1 = input.substring(0,x-1);
int input1Length = input1.length();
boolean[ ] used1 = new boolean[ input1Length ];
char[ ] in = input1.toCharArray( );
doPermute ( in, outputString, used1, input1Length, 0 );
}
public static void doPermute ( char[ ] in, StringBuffer outputString,
boolean[ ] used, int inputLength, int level)
{
if( level == inputLength) {
System.out.println ( outputString.toString());
return;
}
for( int i = 0; i < inputLength; ++i )
{
if( used[i] ) continue;
outputString.append( in[i] );
used[i] = true;
doPermute( in, outputString, used, inputLength, level + 1 );
used[i] = false;
outputString.setLength( outputString.length() - 1 );
}
}
}
帮我提出建议
答案 0 :(得分:0)
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class Permutation {
static int c;
List<String> permutations = new LinkedList<String>();
Scanner sc=new Scanner(System.in);
String input =sc.nextLine();
int conbinationSize = sc.nextInt();
boolean[] isChoosed = new boolean[input.length()];
public void generateCombination(String partialOutput) {
if (partialOutput.length() == conbinationSize) {
permutations.add(partialOutput);
c++;
return;
}
for (int i = 0; i < input.length(); ++i) {
if (!isChoosed[i]) {
isChoosed[i] = true;
generateCombination(partialOutput + input.charAt(i));
isChoosed[i] = false;
}
}
}
void printCombination() {
for (String c : permutations) {
System.out.println(c);
}
}
public static void main(String[] args) {
Permutation dfs = new Permutation();
dfs.generateCombination("");
dfs.printCombination();
System.out.println(c);
}
}