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
| object CombinationSum2 {
def main(args: Array[String]): Unit = { println(combinationSum2(Array(10, 1, 2, 7, 6, 1, 5), 8)) }
def combinationSum2(candidates: Array[Int], target: Int): List[List[Int]] = { val set = Set[List[Int]]() val map = Map[Int, Int]() candidates.foreach(a => map.put(a, (if (map.contains(a)) map.get(a).get else 0) + 1)) backtrack(map, target, 0, new ListBuffer[Int], set) set.toList }
def backtrack(candidates: Map[Int, Int], target: Int, cur: Int, nums: ListBuffer[Int], set: Set[List[Int]]): Unit = { for (c <- candidates.keys) { if (nums.filter(_ == c).size < candidates.get(c).get) { 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 } } } } }
|