Skip to content

Latest commit

ย 

History

History
35 lines (29 loc) ยท 980 Bytes

invidam.go.md

File metadata and controls

35 lines (29 loc) ยท 980 Bytes

Complexity

  • Time complexity: $O(N^t)$

    • target์˜ ํฌ๊ธฐ t์™€ candiates์˜ ํฌ๊ธฐ N์— ๋Œ€ํ•˜์—ฌ, t๋งŒํผ์˜ ์žฌ๊ท€ํ˜ธ์ถœ์ด ์—ฐ์†์ ์œผ๋กœ ์ผ์–ด๋‚  ์ˆ˜ ์žˆ๊ณ  ๊ฐ ํ•จ์ˆ˜์—์„œ ๋ฐฐ์—ด ์ˆœํšŒ ๋น„์šฉ N์ด ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ๋‹ค.
  • Space complexity: $O(N^t)$

    • target์˜ ํฌ๊ธฐ t์™€ candiates์˜ ํฌ๊ธฐ N์— ๋Œ€ํ•˜์—ฌ, ๋ฐฑํŠธ๋ž˜ํ‚น์—์„œ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š” ๋ชจ๋“  ๊ฒฝ์šฐ์˜ ์ˆ˜ ๋งŒํผ ret์ด ์ ์žฌ๋  ์ˆ˜ ์žˆ๋‹ค.

Code

func combinationSum(candidates []int, target int) [][]int {
	sort.Ints(candidates)

	var combination func(candidates []int, target int) [][]int
	combination = func(candidates []int, target int) [][]int {
		if target < 0 {
			return nil
		}
		if target == 0 {
			return [][]int{{}}
		}

		ret := make([][]int, 0)
		for i, c := range candidates {
			items := combination(candidates[i:], target-c)
			for _, item := range items {
				ret = append(ret, append(item, c))
			}
		}
		return ret
	}

	return combination(candidates, target)
}