diff --git a/combination-sum/hyer0705.ts b/combination-sum/hyer0705.ts new file mode 100644 index 000000000..515131a90 --- /dev/null +++ b/combination-sum/hyer0705.ts @@ -0,0 +1,21 @@ +function combinationSum(candidates: number[], target: number): number[][] { + const results: number[][] = []; + + function backtrack(currentIndex: number, sum: number, selected: number[]) { + if (sum > target) return; + if (sum === target) { + results.push([...selected]); + return; + } + + for (let i = currentIndex; i < candidates.length; i++) { + selected.push(candidates[i]); + backtrack(i, sum + candidates[i], selected); + selected.pop(); + } + } + + backtrack(0, 0, []); + + return results; +} diff --git a/decode-ways/hyer0705.ts b/decode-ways/hyer0705.ts new file mode 100644 index 000000000..72969e748 --- /dev/null +++ b/decode-ways/hyer0705.ts @@ -0,0 +1,25 @@ +function numDecodings(s: string): number { + const sLen = s.length; + const isValid = (s: string): boolean => { + if (s[0] === "0") return false; + + return Number(s) > 0 && Number(s) <= 26; + }; + + if (sLen === 0) return 0; + if (s.length === 1) return isValid(s[0]) ? 1 : 0; + + // dp[i]: i번째 위치까지 디코딩할 수 있는 방법의 수 + const dp: number[] = Array(sLen).fill(0); + dp[0] = isValid(s[0]) ? 1 : 0; + dp[1] = (isValid(s[1]) ? dp[0] : 0) + (isValid(s.substring(0, 2)) ? 1 : 0); + + for (let i = 2; i < sLen; i++) { + const singleDigitWays = isValid(s[i]) ? dp[i - 1] : 0; + const doubleDigitWays = isValid(s[i - 1] + s[i]) ? dp[i - 2] : 0; + + dp[i] = singleDigitWays + doubleDigitWays; + } + + return dp[sLen - 1]; +} diff --git a/maximum-subarray/hyer0705.ts b/maximum-subarray/hyer0705.ts new file mode 100644 index 000000000..716b502a6 --- /dev/null +++ b/maximum-subarray/hyer0705.ts @@ -0,0 +1,12 @@ +function maxSubArray(nums: number[]): number { + const numsLen = nums.length; + let currentSum = nums[0]; + let maxSum = nums[0]; + + for (let i = 1; i < numsLen; i++) { + currentSum = Math.max(currentSum + nums[i], nums[i]); + maxSum = Math.max(maxSum, currentSum); + } + + return maxSum; +} diff --git a/number-of-1-bits/hyer0705.ts b/number-of-1-bits/hyer0705.ts new file mode 100644 index 000000000..0b36dd815 --- /dev/null +++ b/number-of-1-bits/hyer0705.ts @@ -0,0 +1,5 @@ +function hammingWeight(n: number): number { + const RADIX = 2; + + return n.toString(RADIX).match(/1/g)?.length || 0; +} diff --git a/valid-palindrome/hyer0705.ts b/valid-palindrome/hyer0705.ts new file mode 100644 index 000000000..3851b4cb2 --- /dev/null +++ b/valid-palindrome/hyer0705.ts @@ -0,0 +1,14 @@ +function isPalindrome(s: string): boolean { + const converted = s.toLowerCase().replace(/[^a-z\d]/g, ""); + + let l = 0; + let r = converted.length - 1; + + while (l < r) { + if (converted[l] !== converted[r]) return false; + l++; + r--; + } + + return true; +}