【LeetCode】46. 全排列:搜索回溯 深度優先遍歷 dfs

在這裏插入圖片描述

這是一道深度優先遍歷的題目。或者說搜索回溯,有狀態標記,有中止條件判定。
public class Solution {
    public List<List<Integer>> permute(int[] nums) {
        int len = nums.length;
        List<List<Integer>> res = new LinkedList<>();
        if (len == 0) {
            return res;
        }
        boolean[] mark = new boolean[len];//標記是否選中
        int depth = 0; // 顯示層數。
        LinkedList<Integer> path = new LinkedList<>();
        dfs(nums, mark, depth, res, len, path);
        return res;
    }

    private void dfs(int[] nums, boolean[] mark, int depth, List<List<Integer>> res, int len, LinkedList<Integer> path) {
        if (depth == len) {
            res.add(new LinkedList<>(path));
            return;
        }

        // 說明還沒有到頭
        for (int i = 0; i < len; i++) {
            if (mark[i]) {
                continue;
            }
            // 說明這個數還沒有被選中
            path.add(nums[i]);
            mark[i] = true;
            depth++;
            dfs(nums, mark, depth, res, len, path);
            depth--;
            mark[i] = false;
            path.removeLast();
        }
    }


}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章