1. 程式人生 > >DFS template and summary

DFS template and summary

normal evel one turned set return sea 學習 ++

最近一直在學習Deep Frist Search,也在leetcode上解了不少的題目。從最開始的懵懂,到現在基本上遇到一個問題有了思路。我現在還清晰的接的今年2月份我剛開始刷提的時候做subsets時那個吃力的勁,腦子就是轉不過來到底該如何的遞歸。

void DFS_no_return(vector<TYPE>& solution_set, TYPE& solution, int idx){
    // DFS terminate condition
    // Normally there are two major categories
    
// One is for some number, already reach this depth according to the question, stop // get to the end of an array, stop if(idx == n || idx == (vector/string).size()){ solution_set.push_back(solution); return; } // very seldom only when our program met some efficiency problem
// do prune to reduce the workload // no need do DFS if we already get the value of current element, just return if(hash_table[input] != hash_table.end()){ return; } for(int i = 0; i < n; i++){ if(visited[i] == 0){ visited[i] = 1; DFS_no_return(solution_set, solution, idx
+ 1); visited[i] = 0; } } return; }

對於有返回值的DFS來說。

TYPE DFS_with_return(int idx){
    // DFS terminate condition
    // Normally there are two major categories
    // One is for some number, already reach this depth according to the question, stop
    // get to the end of an array, stop
    if(idx == n || idx == (vector/string).size()){
        return 1/0/"";
    }
    // very seldom only when our program met some efficiency problem
    // do prune to reduce the workload
    // no need do DFS if we already get the value of current element, just return
    if(hash_table[input] != hash_table.end()){
        return hash_table[input];
    }
    
    TYPE ans;
    for(int i = 0; i < n; i++){
        if(visited[i] == 0){
            // normally, here should to add/concatenate the value in current level with the value returned from lower level
            ans += DFS_no_return(idx + 1);
        }
    }
    // if we need prune
    // keep current value here
    hash_table[input] = ans;
    return ans;
}

總結:

DFS template and summary