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;		// 回溯
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章