2014-12-18 5 views
0

Вот мой код для печати строковых перестановок. Я изо всех сил пытаюсь рассчитать сложность времени функций. Может кто-нибудь предложить несколько указателей. И если есть более эффективный метод времени?сложность перестановки строк печати

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; 
    } 
} 
+0

@DaaaahWhoosh, выглядит рекурсивным - 'merge (перестановка (rest), last)'. – ChiefTwoPencils

+0

@ChiefTwoPencils, поэтому я ненавижу рекурсию, это всегда происходит в одной маленькой строке. Виноват. – DaaaahWhoosh

+0

это должно быть n^2, так как у вас есть вложенный цикл цикла в 'merge' – Sam

ответ

0

Для улучшения скорости, то LinkedList будет быстрее, а также с использованием тех же StringBuffer и StringBuffer#setCharAt(int, char). Что-то вроде этого возможно:

List<String> permutations = new ArrayList<String>(initial size); // initial size to avoid multiple arrays to be created 
if (s.length() == 1) { 
    permutations.add(s); 
} else { 
    StringBuffer sb = new StringBuffer(s); 
    loop { // some kind of loop 
     sb.setCharAt(0, 'a'); // do the next permutation 
     permutations.add(sb.toString()); 
    } 
} 
return permutations; 
+0

LinkedList работает быстрее, и только если вы используете операцию #delete. Попробуйте сами и посмотрите на реализацию LinkedList, чтобы узнать, почему. – dit

+0

Хмм, еще лучше, чем создание нескольких массивов, также можно установить начальный размер для ArrayList. – Bubletan

+0

есть первоначальный размер тоже хорошая идея – dit

0

Обычный merge() is O (n^2). С повторением кажется, что O (n^3)

Смежные вопросы