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
            
            }
        }
    }
}
posted @ 2020-07-22 17:49  ganshuoos  阅读(98)  评论(0编辑  收藏  举报