๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/leetcode

LeetCode 39 - Combination Sum (Medium)

by HandHand 2021. 3. 2.

๋ฌธ์ œ

LeetCode - 39๋ฒˆ

ํ’€์ด ๊ณผ์ •

์ค‘๋ณต ์กฐํ•ฉ ์„ ๋งŒ๋“ค์–ด์„œ ์ˆซ์ž๋“ค์˜ ํ•ฉ์ด target ์ด ๋˜๋Š” ๋ชจ๋“  ๊ฒฝ์šฐ๋ฅผ ์ฐพ๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

์—ฌ๊ธฐ์„œ ์ค‘๋ณต ์กฐํ•ฉ ์ด๋ž€ ์„œ๋กœ ๋‹ค๋ฅธ n๊ฐœ๋ฅผ ์ค‘๋ณต์„ ํ—ˆ์šฉํ•˜์—ฌ r ๊ฐœ๋ฅผ ์„ ํƒํ•˜๋Š” ๊ฒฝ์šฐ ๋ฅผ ๋งํ•ฉ๋‹ˆ๋‹ค.
์ด๋ฅผ ์œ„ํ•ด์„œ๋Š” ๋ฐฑํŠธ๋ž˜ํ‚น ์„ ํ™œ์šฉํ•ด์„œ ๋ชจ๋“  ์กฐํ•ฉ์„ ํƒ์ƒ‰ํ•ด์ฃผ๋Š” ๊ณผ์ •์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค.

๊ธฐ์กด ์กฐํ•ฉ์—์„œ๋Š” i ๋ฒˆ์ฉจ ์ˆซ์ž๋ฅผ ์„ ํƒํ–ˆ์„ ๊ฒฝ์šฐ ๊ทธ ๋‹ค์Œ ์ˆซ์ž์ธ i + 1 ๋ฒˆ์งธ ๋ถ€ํ„ฐ ํ•˜๋‚˜์”ฉ ๊ณจ๋ผ์•ผํ•˜์ง€๋งŒ
์ค‘๋ณต์„ ํ—ˆ์šฉํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์„ ํƒ ์‹œ์ž‘์ ์„ i ๋ฒˆ์งธ ๋ถ€ํ„ฐ ํ•ด์ฃผ๋ฉด ๋ฉ๋‹ˆ๋‹ค.

์ฝ”๋“œ

/**
 * @param {number[]} candidates
 * @param {number} target
 * @return {number[][]}
 */
var combinationSum = function (candidates, target) {
  const answer = [];

  function combination(start, sum, selected) {
    if (sum > target) return;
    else if (sum === target) answer.push(selected);

    for (let i = start; i < candidates.length; i++) {
      combination(i, sum + candidates[i], [...selected, candidates[i]]);
    }
  }

  combination(0, 0, []);
  return answer;
};
๋ฐ˜์‘ํ˜•

'๐Ÿƒ algorithm > leetcode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

LeetCode 240 - Search a 2D Matrix II (Medium)  (0) 2021.03.02
LeetCode 155 - Min Stack (Easy)  (0) 2021.03.02
LeetCode 20 - Valid Parentheses (Easy)  (0) 2021.03.02
LeetCode 787 - Cheapest Flights Within K Stops (Medium)  (0) 2021.03.02
LeetCode 417 - Pacific Atlantic Water Flow (Medium)  (0) 2021.03.02

๐Ÿ’ฌ ๋Œ“๊ธ€