leetcode : Combination Sum II
runtime 0 ms, beats 100% of cpp submissions
O(2^n) solution with explanation
tags: backtracking
๐ link
๐ description
็ตฆๅฎไธๅ้ฃๅ candidates ๏ผ่้่ฆ็ตๅ็ target ๏ผ่ซๆฑๆๆๅฏ่ฝ็็ตๅๆนๅผใ
ex. Input: candidates = [10,1,2,7,6,1,5], target = 8 Output: [ [1,1,6], [1,2,5], [1,7], [2,6] ]
๐ง solution
Combination Sum
Combination Sum solution
Combination Sum ้ก็ฎ็้ฒๅ็๏ผๆฏๅๅ
็ด ๅฎๆฌกๆฟๅ๏ผไธ่ฆๆฑ็ตๅไธ่ฝ้่คใ
้ๅฐ็ๆๅฏ่ฝ็ตๅ็ๆนๅผ๏ผไธฆๆฒๆๅคชๅค็่ฎๅ๏ผ้่ฆ่็็้จๅๆฏ็ตๅไธ่ฝ้่ค๏ผๆไปฅไธๅ ฉๅๆนๆณ
- ไฝฟ็จ set ๅป้ (็กๆณไฝฟ็จ hashset ๏ผๅ ็บ c++ ไธๆฏๆด hashset ้ๅฐ vector ็็ดขๅผ)
- sort candidates ๅจ็ตๅ็้็จไธญๅคๆทไธฆ้ฟๅ ้่ค็ตๅใ
็ฌฌไธ็จฎๆนๆณๅฏฆไฝ้ๅธธ็ฐกๅฎ๏ผไฝๆฏๆๅ ฉๅ็ผบ้ป
- ้่ฆไฝฟ็จ้กๅค็ฉบ้
- ๆ้ฒๅ ฅ้่ค็็ตๅไธญ๏ผๅขๅ ่จ็ฎ้
่็ฌฌไบ็จฎๆนๆณๅ้่ฆ sort candidates ๏ผ่จ็ฎ้็ธๅฐ่ผๅฐ
โณ time complexity
ๅฐ candidates ๆๅบ๏ผๆ้่ค้ๅบฆ O(nlog(n))
ๅๆๅฐๆพๅฏ่ฝ็ตๅ๏ผๆฏๅๅ
็ด ๅฏ่ฝๆฟๅฏ่ฝไธๆฟ๏ผๆ้่ค้ๅบฆ O(2^n)
็ธฝๆ้่ค้ๅบฆ O(2^n)
๐ code
1 | class Solution { |