• leetcode刷题笔记七十七题 组合


    leetcode刷题笔记七十七题 组合

    源地址:77. 组合

    问题描述:

    给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。

    示例:

    输入: n = 4, k = 2
    输出:
    [
    [2,4],
    [3,4],
    [2,3],
    [1,2],
    [1,3],
    [1,4],
    ]

    /**
    本题可通过回溯法解决,使用的是与全排列类似的深度优先遍历方法
    在遍历过程中使用剪枝
    */
    import scala.collection.mutable
    import util.control.Breaks._
    object Solution {
        def combine(n: Int, k: Int): List[List[Int]] = {
    
            var res = mutable.ListBuffer[List[Int]]()
            var path = mutable.ListBuffer[Int]()
    
            if( n == 0 || k == 0 || n < k) return List()
            dfs(n, k, 1, path, res)
            return res.toList
        }
    
        def dfs(n: Int, k: Int, depth: Int, path: mutable.ListBuffer[Int], res: mutable.ListBuffer[List[Int]]): Unit = {
            
            if(path.length == k){
                res += path.toList
                return
            }
    
            breakable{
                //这里进行剪枝
                for(i <- depth to n - (k - path.length) + 1){             
                    path += i
                    //这里使用i+1,将小于等于i的数字排除
                    dfs(n, k, i+1, path, res)
                    path -= i
                
                }
            }
        }
    }
    
  • 相关阅读:
    XML入门
    BOM编程
    hdfs高可用
    Hadoop搭建问题及解决方案 --持续更新
    hadoop3完全分布式搭建
    hadoop环境搭建笔记
    hadoop3.x介绍
    基于JavaAPI对远程hdfs的操作
    13. Roman to Integer C++
    9. Palindrome Number(回文数)C++
  • 原文地址:https://www.cnblogs.com/ganshuoos/p/13362247.html
Copyright © 2020-2023  润新知