深度优先搜索算法dfs

深度优先,亦称回溯算法。先沿着某一线路进行搜索,达到条件时返回,切换另一条线路。

treeSearch.jpg

该算法可以涵盖所有情况,对于搜索比较适合。
如数组,tree搜索

Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.

Note:

All numbers will be positive integers.
The solution set must not contain duplicate combinations.
Example 1:

Input: k = 3, n = 7
Output: [[1,2,4]]
Example 2:

Input: k = 3, n = 9
Output: [[1,2,6], [1,3,5], [2,3,4]]

//javascript
var combinationSum3 = function(k, n) {
    let res=[]
    let temp=[]
    if(k===0) return [];
    if(n/k>9)return [];
    dfs(res,temp,n,k,1)
    return res
};

function dfs(res,temp,remain,num,cur){

    if(remain<0) return
    //当达到k的阈值
    if(num===0){
     if(remain===0){
         let tmp=temp.slice(0,temp.length);//数组拷贝
         res.push(tmp)
     }
    return
    }
    for(let i=cur;i<=9;i++){
        temp[temp.length]=i;
        //搜索下一个值
        dfs(res,temp,remain-i,num-1,i+1);
        temp.pop()
    }
}

另外一个关于二叉树搜索的dfs问题

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 图的遍历 图的遍历为从图中某一顶点出发访遍图中其余顶点,且使每一个顶点仅被访问一次的过程。 对于图的遍历,不想树那...
    NotFunGuy阅读 2,644评论 0 1
  • 深度优先搜索算法(DFS) 标签(空格分隔): algorithm 1.深度优先搜索算法(Deep Fisrt S...
    别时茫茫阅读 10,963评论 3 8
  • Introduction What is Bowtie 2? Bowtie 2 is an ultrafast a...
    wzz阅读 5,816评论 0 5
  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 9,505评论 0 13
  • 昨天接近夏天的节奏 气温高达28度 虽不是大晴天 云层遮挡不了太阳的热辣 风是热乎乎的 动辄一身汗水 街上摇曳款款...
    一树丁香阅读 713评论 10 8