Number.46——全排列

题目链接:https://leetcode-cn.com/problems/permutations/

给定一个 没有重复 数字的序列,返回其所有可能的全排列。

示例:

输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]

官方题解(有视频)https://leetcode-cn.com/problems/permutations/solution/quan-pai-lie-by-leetcode-solution-2/

想起了算法设计与分析课里面老师讲的分治法

class Solution {
    private List<List<Integer>> result = new ArrayList<List<Integer>>();
    public List<List<Integer>> permute(int[] nums) {
        perm(nums, 0, nums.length - 1);
        return result;
    }
    public void perm(int[] nums, int start, int end){
        if (start == end){
            ArrayList<Integer> res = new ArrayList<>();
            for (int num : nums){
                res.add(num);
            }
            result.add(res);
        }

        for (int i = start; i <= end; i++){
            swap(nums, start, i);
            perm(nums, start + 1, end);
            swap(nums, start, i);
        }
    }

	// java 的 swap 函数要注意
    private void swap(int[] nums, int l, int r){
        int temp = nums[l];
        nums[l] = nums[r];
        nums[r] = temp;
    }
}

还有题解中的回溯法,因为回溯法不熟,所以代码也贴在这,题解视频讲的非常清楚,就不写了:

class Solution {
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        int len = nums.length;
        if (len == 0){
            return result;
        }

        List<Integer> path = new ArrayList<>();	// 记录每一种排列
        boolean[] used = new boolean[len];		// 记录原数组中的数是否被用过,以空间换时间
        dfs(nums, len, 0, path, used, result);
        return result;
    }

    public void dfs(int[] nums, int len, int depth, List<Integer> path, boolean[] used, List<List<Integer>> result){
        if (depth == len){
            result.add(new ArrayList<>(path));	// 注意要拷贝一下path,不然path会是空的
            return;
        }
        for (int i = 0; i < len; i++){
            if (used[i]){	// 如果该数被用过,直接跳过
                continue;
            }
            path.add(nums[i]);
            used[i] = true;
            dfs(nums, len, depth + 1, path, used, result);
            path.remove(path.size() - 1);	// 回溯
            used[i] = false;		// 回溯
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章