JAVAアルゴリズム:重複する数字のないシーケンスを指定し、可能なすべての配列を返します(JAVAバージョン)
1987 ワード
JAVAアルゴリズム:重複する数字のないシーケンスを指定し、その可能なすべての全配列を返します.
プログラムの実行結果:
[1, 2, 3, 4] [1, 2, 4, 3] [1, 3, 2, 4] [1, 3, 4, 2] [1, 4, 3, 2] [1, 4, 2, 3] [2, 1, 3, 4] [2, 1, 4, 3] [2, 3, 1, 4] [2, 3, 4, 1] [2, 4, 3, 1] [2, 4, 1, 3] [3, 2, 1, 4] [3, 2, 4, 1] [3, 1, 2, 4] [3, 1, 4, 2] [3, 4, 1, 2] [3, 4, 2, 1] [4, 2, 3, 1] [4, 2, 1, 3] [4, 3, 2, 1] [4, 3, 1, 2] [4, 1, 3, 2] [4, 1, 2, 3]
package com.bean.algorithm.basic;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class PermuteRecursionNumber {
private void swap(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
private void permuteRecursion(int[] nums, int start, int end, Integer[] nums_Integer, List> result) {
if (start == end) {
/*
* for(int i = 0; i temp = new ArrayList(Arrays.asList(nums_Integer));
result.add(temp);
}
for (int i = start; i <= end; i++) {
/* start i */
swap(nums, start, i);
permuteRecursion(nums, start + 1, end, nums_Integer, result);
/* start i */
swap(nums, start, i);
}
}
public List> permute(int[] nums) {
List> result = new ArrayList<>();
Integer[] nums_Integer = new Integer[nums.length];
permuteRecursion(nums, 0, nums.length - 1, nums_Integer, result);
return result;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
PermuteRecursionNumber prn = new PermuteRecursionNumber();
int[] nums = new int[] { 1, 2, 3, 4 };
List> list = prn.permute(nums);
Iterator> itx = list.iterator();
while (itx.hasNext()) {
List lt = itx.next();
System.out.println(lt);
}
System.out.println();
}
}
プログラムの実行結果:
[1, 2, 3, 4] [1, 2, 4, 3] [1, 3, 2, 4] [1, 3, 4, 2] [1, 4, 3, 2] [1, 4, 2, 3] [2, 1, 3, 4] [2, 1, 4, 3] [2, 3, 1, 4] [2, 3, 4, 1] [2, 4, 3, 1] [2, 4, 1, 3] [3, 2, 1, 4] [3, 2, 4, 1] [3, 1, 2, 4] [3, 1, 4, 2] [3, 4, 1, 2] [3, 4, 2, 1] [4, 2, 3, 1] [4, 2, 1, 3] [4, 3, 2, 1] [4, 3, 1, 2] [4, 1, 3, 2] [4, 1, 2, 3]