使用K個數字(< 10)組成和爲N的組合

這個題目能夠用遞歸的方式求解,設combineSum(k, n)表示用k個數字和爲n的組合數,那麼能夠用來求解combineSum(k + 1, n + x) [x >= 1 && x <= 9],將x添加到每個組合的頭部便可;
scala

代碼以下:code

def combinationSumK(k: Int, n: Int): List[List[Int]] = {

  def go(k: Int, n: Int, x: Int): List[List[Int]] =
    if (k == 1) List(List(n))
    else {
      for {
        i <- (x + 1 until 10).toList
        if (n - i > i)
        list <- go(k - 1, n - i, i)
      } yield i :: list
    }

  go(k, n, 0)
}

println(combinationSumK(3, 9))
println(combinationSumK(4, 24))

這裏的實現是使用combineSum(k, n, x)來表示的,x用來限定組合裏面數字的起始值,這樣能夠起到排序和避免重複的做用;排序

相關文章
相關標籤/搜索