题解 | #牛群排队#

牛群排队

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);
            }
        }
    }
}

全部评论

相关推荐

乐观的打工人前程似锦:怎么说呢🤔️,学历够,专业技能看起来也有那么回事,就是项目会不会差点?dji更喜欢较为复杂的工程落地的项目吧?如果有一些title的项目就更好了。有实习也是加分项,搞过神经网络应该也是加分项。进面应该可以,还是要看技术过硬
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务