(UVA) Knuth's Permutation - Solution
Link to the problem: https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=646&page=show_problem&problem=1004
The solution below used Backtracking to solve this problem.
import java.io.*;
import java.util.*;
class Main {
public String sequence;
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
public void rec(int index, char[] array) throws NumberFormatException, IOException {
if (index == sequence.length()) {
for (int i = 0; i < array.length; i++) {
bw.write(array[i]);
}
bw.write("\n");
return;
}
for (int j = index; j > 0; j--) {
array[j] = array[j-1];
}
array[0] = sequence.charAt(index);
rec(index+1, array);
for (int i = 1; i <= index; i++) {
char tmp = array[i];
array[i] = array[i-1];
array[i-1] = tmp;
rec(index+1, array);
}
}
public void process() throws NumberFormatException, IOException {
Scanner sc = new Scanner(System.in);
int numCase = 0;
while (sc.hasNext()) {
if (numCase > 0) {
bw.write("\n");
}
sequence = sc.next();
char[] array = new char[sequence.length()];
rec(0, array);
numCase++;
}
bw.flush();
bw.close();
return;
}
public static void main(String[] args) throws NumberFormatException, IOException {
Main m = new Main();
m.process();
System.exit(0);
}
}
The solution below used Backtracking to solve this problem.
import java.io.*;
import java.util.*;
class Main {
public String sequence;
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
public void rec(int index, char[] array) throws NumberFormatException, IOException {
if (index == sequence.length()) {
for (int i = 0; i < array.length; i++) {
bw.write(array[i]);
}
bw.write("\n");
return;
}
for (int j = index; j > 0; j--) {
array[j] = array[j-1];
}
array[0] = sequence.charAt(index);
rec(index+1, array);
for (int i = 1; i <= index; i++) {
char tmp = array[i];
array[i] = array[i-1];
array[i-1] = tmp;
rec(index+1, array);
}
}
public void process() throws NumberFormatException, IOException {
Scanner sc = new Scanner(System.in);
int numCase = 0;
while (sc.hasNext()) {
if (numCase > 0) {
bw.write("\n");
}
sequence = sc.next();
char[] array = new char[sequence.length()];
rec(0, array);
numCase++;
}
bw.flush();
bw.close();
return;
}
public static void main(String[] args) throws NumberFormatException, IOException {
Main m = new Main();
m.process();
System.exit(0);
}
}
Comments
Post a Comment