class{ publicvoidbacktrack(int n, ArrayList<Integer> nums, List<List<Integer>> output, int first){ // 如果所有的整数都参与排列了 if (first == n) output.add(new ArrayList<Integer>(nums)); //开始遍历索引first到索n-1的所有整数。 for (int i = first; i < n; i++) { // 在当前的一种排列中,交换第i个元素和first元素的位置 Collections.swap(nums, first, i); // 用下一个整数进行回溯生成排列 backtrack(n, nums, output, first + 1); // 恢复交换的两个元素 Collections.swap(nums, first, i); } }
public List<List<Integer>> permute(int[] nums) { List<List<Integer>> output = new LinkedList();
//将数组转化成列表 ArrayList<Integer> nums_lst = new ArrayList<Integer>(); for (int num : nums) nums_lst.add(num); int n = nums.length; backtrack(n, nums_lst, output, 0); return output; } }
近期评论