Sat May 6 01:33:00 UTC 2023 inscode

上级 5b0ce43e
class Main {
import java.util.ArrayList;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
int[] arr = {1, 2, 3};
ArrayList<ArrayList<Integer>> result = Permutations.permute(arr);
System.out.println(result);
}
}
\ No newline at end of file
import java.util.ArrayList;
import java.util.Arrays;
public class Permutations {
public static void main(String[] args) {
int[] arr = {1, 2, 3};
ArrayList<ArrayList<Integer>> result = permute(arr);
System.out.println(result);
}
public static ArrayList<ArrayList<Integer>> permute(int[] nums) {
ArrayList<ArrayList<Integer>> result = new ArrayList<>();
if (nums == null || nums.length == 0) {
return result;
}
ArrayList<Integer> list = new ArrayList<Integer>();
Arrays.sort(nums);
boolean[] used = new boolean[nums.length];
helper(result, list, nums, used);
return result;
}
public static void helper(ArrayList<ArrayList<Integer>> result, ArrayList<Integer> list, int[] nums, boolean[] used) {
if (list.size() == nums.length) {
result.add(new ArrayList<Integer>(list));
return;
}
for (int i = 0; i < nums.length; i++) {
if (used[i] || (i > 0 && nums[i] == nums[i - 1] && !used[i - 1])) {
continue;
}
used[i] = true;
list.add(nums[i]);
helper(result, list, nums, used);
used[i] = false;
list.remove(list.size() - 1);
}
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册