Вложенный массив Java в метод рекурсии

Вот мой код, который используется для поиска всех комбинаций из массива. Есть ли рекурсивный способ повысить гибкость кодирования?

Результат здесь: 1324 1342 1234 1243 1432 1423 3124 3142 3214 3241 3412 3421 2134 2143 2314 2341 2413 2431 4132 4123 4312 4321 4213 4231

class Main {

  // Find all combination from an array
  public static void findAllConbinationFromArray(int ary[]){
    for(int i = 0 ; i < ary.length ; i++){
      for(int j = 0 ; j < ary.length ; j++){
        for(int k = 0 ; k < ary.length ; k++){
          for(int l = 0 ; l < ary.length ; l++){
            if(check(i, j, k, l)){
              System.out.print(ary[i] + "" + ary[j] + "" + ary[k] + "" + ary[l]);
              System.out.println(); 
            }
          }
        }
      }
    }
  }

  // Check and skip if it selects same value
  public static boolean check(int ... elemt){

    for(int i = 0 ; i < elemt.length ; i++){
      int current = elemt[i];
      for(int j = 0 ; j < elemt.length ; j ++){
        if(i != j){
          if(current == elemt[j])
            return false;
        }
      }
    }
    return true;
  }

  public static void main(String[] args) {
    int ary[] = {1, 3, 2, 4};
    findAllConbinationFromArray(ary);
  }
}

person alantheweasel    schedule 27.08.2017    source источник
comment
Возможный дубликат Выполните все перестановки массива рекурсивно   -  person user3437460    schedule 27.08.2017


Ответы (1)


Это рекурсивный способ создания всех перестановок массива.

public class Permute {

void swap(int[] arr, int x, int y) {
    int temp = arr[x];
    arr[x] = arr[y];
    arr[y] = temp;
}

void permute(int[] arr) {
    permute(arr, 0, arr.length - 1);
}

//i - start index
//n - end index
void permute(int[] arr, int i, int n) {
    int j;
    if (i == n)
        System.out.println(Arrays.toString(arr));
    else {
        for (j = i; j <= n; j++) {
            swap(arr, i, j);
            permute(arr, i + 1, n);
            swap(arr, i, j); // swap back
        }
    }
}

public static void main(String[] args) {
    int arr[] = { 1, 2, 3, 4 };
    new Permute().permute(arr);
}

}

person Chamin Wickramarathna    schedule 27.08.2017
comment
Пожалуйста. Если это правильный ответ, не стесняйтесь ставить флажок правильного ответа;) - person Chamin Wickramarathna; 27.08.2017
comment
И есть ли у вас нерекурсивный способ эффективно решить эту проблему? - person alantheweasel; 27.08.2017
comment
@alantheweasel Если вам нужен лучший способ решить эту проблему нерекурсивно, вам придется задать еще один вопрос. - person user3437460; 27.08.2017
comment
@alantheweasel, этот пост вам поможет. stackoverflow.com/questions/2799078/ - person Chamin Wickramarathna; 27.08.2017