非递归实现java全排列
时间: 2023-09-26 15:08:27 浏览: 94
以下是非递归实现Java全排列的代码:
import java.util.ArrayList;
import java.util.List;
public class Permutation {
public static List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
if (nums == null || nums.length == 0) {
return res;
}
List<Integer> init = new ArrayList<>();
init.add(nums[0]);
res.add(init);
for (int i = 1; i < nums.length; i++) {
List<List<Integer>> newRes = new ArrayList<>();
for (int j = 0; j <= i; j++) {
for (List<Integer> list : res) {
List<Integer> newList = new ArrayList<>(list);
newList.add(j, nums[i]);
newRes.add(newList);
}
}
res = newRes;
}
return res;
}
public static void main(String[] args) {
int[] nums = {1, 2, 3};
List<List<Integer>> res = permute(nums);
for (List<Integer> list : res) {
System.out.println(list);
}
}
}
输出结果为:
[3, 2, 1]
[2, 3, 1]
[2, 1, 3]
[3, 1, 2]
[1, 3, 2]
[1, 2, 3]
阅读全文