题解 | #牛群排队#
牛群排队
https://www.nowcoder.com/practice/8d8ae3937cd5466eb330ca484ca5ed80
知识点:回溯
思路:经典的回溯解决全排列的问题
编程语言:java
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param nums int整型一维数组 * @return int整型二维数组 */ public int[][] cow_permute(int[] nums) { List<List<Integer>> result = new ArrayList<>(); List<Integer> tempList = new ArrayList<>(); boolean[] used = new boolean[nums.length]; backtrack(nums, used, tempList, result); int[][] output = new int[result.size()][nums.length]; for (int i = 0; i < result.size(); i++) { for (int j = 0; j < nums.length; j++) { output[i][j] = result.get(i).get(j); } } return output; } private void backtrack(int[] nums, boolean[] used, List<Integer> tempList, List<List<Integer>> result) { if (tempList.size() == nums.length) { result.add(new ArrayList<>(tempList)); } else { for (int i = nums.length-1; i >=0; i--) { if (used[i]) continue; tempList.add(nums[i]); used[i] = true; backtrack(nums, used, tempList, result); used[i] = false; tempList.remove(tempList.size() - 1); } } } }