1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| object CombinationSum {
def main(args: Array[String]): Unit = { println(combinationSum(Array(2, 3, 6, 7), 7)) println(combinationSum(Array(2, 7, 6, 3, 5, 1), 9)) }
def combinationSum(candidates: Array[Int], target: Int): List[List[Int]] = { val set = Set[List[Int]]() backtrack(candidates, target, 0, new ListBuffer[Int], set) set.toList }
def backtrack(candidates: Array[Int], target: Int, cur: Int, nums: ListBuffer[Int], set: Set[List[Int]]): Unit = { for (c <- candidates) { if (cur + c == target) { val listT = new ListBuffer[Int]() listT ++= nums listT += c set += listT.sortWith((a, b) => if (a - b < 0) true else false).toList } else if (cur + c < target) { nums += c backtrack(candidates, target, cur + c, nums, set) nums -= c } } }
}
|