code.ashish.me

Atom feed

Recently added: 02 Count Of Subset Sum, 416 Partition Equal Subset Sum, 01 Subset Sum, 518 Coin Change 2, 983 Minimum Cost For Tickets

10 Combination Sum 3

/**
 *
 * Ashish Patel
 * e: ashishsushilPatel@gmail.com
 * w: https://ashish.me
 *
 */

const combinationSum3 = (k, target) => {
  const result = []
  const backtrack = (index, curr, sum) => {
    if (curr.length == k) {
      if (sum == target) {
        result.push(curr.slice())
      }
      return
    }
    if (sum > target) {
      return
    }
    for (let i = index; i < 10; i++) {
      sum += i
      curr.push(i)
      backtrack(i + 1, curr, sum)
      curr.pop()
      sum -= i
    }
  }
  backtrack(1, [], 0)
  return result
}

console.log(combinationSum3(3, 7))

Created 2022-02-26T16:34:43+00:00 · Edit