Skip to content

[hsskey] WEEK 03 solutions #1289

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Apr 19, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions combination-sum/hsskey.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/**
* @param {number[]} candidates
* @param {number} target
* @return {number[][]}
*/
var combinationSum = function(candidates, target) {
const result = []
function backtrack(start, curr, sum) {
// 현재 합계가 타겟과 같으면 결과에 추가
if(sum === target) {
result.push([...curr])
}

// 합계가 타겟을 초과하면 더 이상 진행하지 않음
if(sum > target) {
return
}

// 현재 인덱스부터 시작하여 모든 후보를 시도
for(let i = start; i < candidates.length; i++) {
curr.push(candidates[i])
// 같은 숫자를 여러 번 사용할 수 있으므로 i부터 다시 시작
backtrack(i, curr, sum + candidates[i])
curr.pop()
}
}
backtrack(0, [], 0)
return result
};
53 changes: 53 additions & 0 deletions decode-ways/hsskey.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/**
* @param {string} s
* @return {number}
*/
var numDecodings = function(s) {
if (s[0] === '0') return 0;

let count = 0;
const memo = {};

function backtrack(index, curr) {
// 기저 조건: 문자열 끝까지 왔으면 유효한 디코딩 발견
if (index === s.length) {
count++;
return;
}

// 메모이제이션 키 생성
const key = index;
if (memo[key] !== undefined) {
count += memo[key];
return;
}

// 이전 카운트 저장
const prevCount = count;

// Case 1: 한 자리 숫자로 디코딩 (1~9)
if (s[index] !== '0') {
const oneDigit = s[index];
curr.push(oneDigit);
backtrack(index + 1, curr);
curr.pop();
}

// Case 2: 두 자리 숫자로 디코딩 (10~26)
if (index + 1 < s.length) {
const twoDigit = s.substring(index, index + 2);
const num = parseInt(twoDigit);
if (num >= 10 && num <= 26) {
curr.push(twoDigit);
backtrack(index + 2, curr);
curr.pop();
}
}

// 현재 위치에서 발견한 디코딩 방법 수 저장
memo[key] = count - prevCount;
}

backtrack(0, []);
return count;
};
15 changes: 15 additions & 0 deletions maximum-subarray/hsskey.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/**
* @param {number[]} nums
* @return {number}
*/
var maxSubArray = function(nums) {
let maxSum = -Infinity
let currentSum = 0

for(let num of nums) {
currentSum = Math.max(num, currentSum + num)
maxSum = Math.max(maxSum, currentSum)
}

return maxSum
};
23 changes: 23 additions & 0 deletions number-of-1-bits/hsskey.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/**
* @param {number} n
* @return {number}
*/
var hammingWeight = function(n) {
function recursive(num) {
// 종료조건
if(String(num) === '1') {
return '1'
}
// 재귀호출
const q = Math.floor(num / 2) // 몫
const r = num % 2 // 나머지
const total = r + recursive(q)

// 데이터 통합
return total
}
const binaryString = recursive(n)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

직접 2진수로 변환해서 문자열로 만들어주는 방법도 있지만
동일한 변환 로직을 사용하는 toString 메소드도 있어서 코멘트 남겨봅니다 😊
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Number/toString

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

리뷰주셔서 감사합니다. 직관적으로 떠올린 풀이는 재귀적으로 푸는 현재와 같은 풀이였는데
말씀주신 방법도 다시 한번 풀어보며 다른 풀이도 익숙해질수있게 확인해봐야겠네요 감사합니다 😊

const result = [...binaryString].map(Number).reduce((a,b) => a + b, 0)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

각 숫자들을 더한 결과로 1의 개수를 세는 것은 생각지 못했던 방법이네요..!! 😲


return result
};
10 changes: 10 additions & 0 deletions valid-palindrome/hsskey.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/**
* @param {string} s
* @return {boolean}
*/
var isPalindrome = function(s) {
const cleanStr = s.toLowerCase().replace(/[^a-z0-9]/g, '')
const reversedStr = [...cleanStr].reverse().join('')

return cleanStr === reversedStr
};