题解 | #牛群排队#
牛群排队
https://www.nowcoder.com/practice/8d8ae3937cd5466eb330ca484ca5ed80
知识点:回溯
这道题考查的是全排列问题,题目中已说明无重复元素,故我们在遍历时就可以对已经遍历过的元素进行判断,若已存在则跳过,直至整个数组的元素存入列表中。
题目要求要倒序排序,故我们可以先对数组进行升序排序,再从后往前进行遍历。
Java题解如下
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param nums int整型一维数组 * @return int整型二维数组 */ private List<List<Integer>> res = new ArrayList<>(); private int[] nums; public int[][] cow_permute (int[] nums) { // write code here Arrays.sort(nums); this.nums = nums; backTracking(0, new ArrayList<>()); int[][] ans = new int[res.size()][nums.length]; for(int i = 0; i < res.size(); i++) { for(int j = 0; j < nums.length; j++) { ans[i][j] = res.get(i).get(j); } } return ans; } private void backTracking(int index, List<Integer> list) { for(int i = nums.length - 1; i >= 0; i--) { if(list.contains(nums[i])) { continue; } list.add(nums[i]); if(list.size() == nums.length) { res.add(new ArrayList<>(list)); }else { backTracking(index + 1, list); } list.remove(list.size() - 1); } } }