Вот мой код для печати строковых перестановок. Я изо всех сил пытаюсь рассчитать сложность времени функций. Может кто-нибудь предложить несколько указателей. И если есть более эффективный метод времени?сложность перестановки строк печати
import java.util.ArrayList;
public class Permutations {
public static void main(String[] args){
ArrayList<String> aList = permutation("ABCC");
for(int i=0; i<aList.size(); i++){
System.out.print(aList.get(i) + " ");
}
}
public static ArrayList<String> permutation(String s) {
// The result
ArrayList<String> res = new ArrayList<String>();
// If input string's length is 1, return {s}
if (s.length() == 1) {
res.add(s);
} else if (s.length() > 1) {
int lastIndex = s.length() - 1;
// Find out the last character
String last = s.substring(lastIndex);
// Rest of the string
String rest = s.substring(0, lastIndex);
// Perform permutation on the rest string and
// merge with the last character
res = merge(permutation(rest), last);
}
return res;
}
public static ArrayList<String> merge(ArrayList<String> list, String c) {
ArrayList<String> res = new ArrayList<String>();
// Loop through all the string in the list
for (String s : list) {
// For each string, insert the last character to all possible postions
// and add them to the new list
for (int i = 0; i <= s.length(); ++i) {
String ps = new StringBuffer(s).insert(i, c).toString();
res.add(ps);
}
}
return res;
}
}
@DaaaahWhoosh, выглядит рекурсивным - 'merge (перестановка (rest), last)'. – ChiefTwoPencils
@ChiefTwoPencils, поэтому я ненавижу рекурсию, это всегда происходит в одной маленькой строке. Виноват. – DaaaahWhoosh
это должно быть n^2, так как у вас есть вложенный цикл цикла в 'merge' – Sam