dfs(深度優先搜索算法)的一些總結

dfs解決全排列問題

解決思路: 每個數字如果訪問了,就標記一下,之後,對剩餘沒有訪問的數字再次進行訪問,之後,再對該數字取消標記,以便讓數字得到訪問

數字的全排列的函數如下所示:

class Node
    {
        int num = 0;
        boolean outHand = false;
    }
    List<Node> nodeList =  new ArrayList<>();
    List<Integer> lists = new ArrayList<>();
    int total = 0;
    void dfs(int step, int n)
    {
        if (step == n )
        {

            for (int i = 0; i < n; i++)
            {
                System.out.print(nodeList.get(i).num);
            }
            total++;
            System.out.println();
            return;
        }
        for (int i = 0; i < n; i++)
        {
            if (nodeList.get(i).outHand == false)
            {
                nodeList.get(step).num = i;
                nodeList.get(i).outHand = true;
                dfs(step + 1, n);
                nodeList.get(i).outHand = false;
            }
        }

        return;
    }

    public Node inner()
    {
        return new Node();
    }

組合

組合的話,其實加上一個過濾條件,就是當前的順序要大於上一次的順序即可,字符串的組合函數如下所示

/**
     * @Author miaoxu
     * @Description
     * 字符串組合函數
     * @Date 23:05 2018/9/4
     * @Param [num 總數中選擇幾個數字, tem 臨時字符串, res 結果所存的字符集, step, n, flag, string, last 上一次抽取的字符串的位置]
     * @return void
     **/
    public void dfs_strCom(int num,String tem, List<String> res, int step, int n, boolean[] flag, String string, int last)
    {
        if (step == num)
        {
            res.add(tem);
            return;
        }
        for (int i = 0; i < string.length(); i++)
        {
            if (flag[i] == false && i > last)
            {
                flag[i] = true;
                dfs_strCom(num,tem +string.charAt(i), res, step + 1,n, flag, string, i);
                flag[i] = false;
            }
        }
    }

網上的dfs的思路模板

bool check() {
    if(滿足條件) {
        return true;
    }
    return false;
}

void dfs(int step) {
    判斷邊界條件(找到||找完) {
        結束    
    }

    {
        判斷所有的可能性
        滿足check的條件
        標記
        繼續進行下一步(step+1)
        去掉標記(即回溯)
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章