-
-
Notifications
You must be signed in to change notification settings - Fork 195
[재호] WEEK 03 Solutions #375
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
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
2c5b297
solve: two sum
wogha95 6f4e4dc
Merge branch 'DaleStudy:main' into main
wogha95 ed2b469
solve: climbing stairs
wogha95 d21692f
solve: climbing stairs
wogha95 b47d55b
solve: product of array except self
wogha95 9e90dec
solve: combination sum
wogha95 6e8760c
solve: coin change
wogha95 5264f19
solve: combination sum
wogha95 7788008
solve: combination sum
wogha95 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
// DP 활용하였고 메모리 축소를 위해 현재와 직전의 경우의 수만 관리하였습니다. | ||
// TC: O(N) | ||
// SC: O(1) | ||
|
||
/** | ||
* @param {number} n | ||
* @return {number} | ||
*/ | ||
var climbStairs = function (n) { | ||
let previousStep = 0; | ||
let currentStep = 1; | ||
|
||
while (n > 0) { | ||
n -= 1; | ||
const nextStep = previousStep + currentStep; | ||
previousStep = currentStep; | ||
currentStep = nextStep; | ||
} | ||
|
||
return currentStep; | ||
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
// TC: O(C * A) | ||
// SC: O(C) | ||
// C: coins.length, A: amount | ||
|
||
/** | ||
* @param {number[]} coins | ||
* @param {number} amount | ||
* @return {number} | ||
*/ | ||
var coinChange = function (coins, amount) { | ||
const dp = new Array(amount + 1).fill(Number.MAX_SAFE_INTEGER); | ||
dp[0] = 0; | ||
|
||
for (let index = 1; index < amount + 1; index++) { | ||
for (const coin of coins) { | ||
if (index - coin >= 0) { | ||
dp[index] = Math.min(dp[index - coin] + 1, dp[index]); | ||
} | ||
} | ||
} | ||
|
||
return dp[amount] === Number.MAX_SAFE_INTEGER ? -1 : dp[amount]; | ||
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,84 @@ | ||
// 2차 | ||
// 몫을 활용하여 시간복잡도를 줄이고자 하였으나 generateSubResult에서 추가 시간발생으로 유의미한 결과를 발견하지 못했습니다. | ||
// TC: O(C^2 * T) | ||
// SC: O(T) | ||
// C: candidates.length, T: target | ||
|
||
/** | ||
* @param {number[]} candidates | ||
* @param {number} target | ||
* @return {number[][]} | ||
*/ | ||
var combinationSum = function (candidates, target) { | ||
const result = []; | ||
// 'q' means 'quotient'. | ||
const qList = candidates.map((candidate) => Math.floor(target / candidate)); | ||
|
||
dfs([], 0); | ||
|
||
return result; | ||
|
||
function dfs(selectedQList, total) { | ||
if (total > target) { | ||
return; | ||
} | ||
|
||
if (total === target) { | ||
result.push(generateSubResult(selectedQList)); | ||
return; | ||
} | ||
|
||
const currentIndex = selectedQList.length; | ||
for (let q = qList[currentIndex]; q >= 0; q--) { | ||
selectedQList.push(q); | ||
dfs(selectedQList, total + candidates[currentIndex] * q); | ||
selectedQList.pop(); | ||
} | ||
} | ||
|
||
function generateSubResult(selectedQList) { | ||
return selectedQList | ||
.map((q, index) => new Array(q).fill(candidates[index])) | ||
.flat(); | ||
} | ||
}; | ||
|
||
// 1차 | ||
// dfs를 활용하여 각 요소를 추가 -> 재귀 -> 제거 -> 재귀로 순회합니다. | ||
// TC: O(C^T) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 시간 복잡도를 어떻게 There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. |
||
// SC: O(C) | ||
// C: candidates.length, T: target | ||
|
||
/** | ||
* @param {number[]} candidates | ||
* @param {number} target | ||
* @return {number[][]} | ||
*/ | ||
var combinationSum = function (candidates, target) { | ||
const result = []; | ||
|
||
dfs([], 0, 0); | ||
|
||
return result; | ||
|
||
function dfs(subResult, total, currentIndex) { | ||
if (total > target) { | ||
return; | ||
} | ||
|
||
if (total === target) { | ||
result.push([...subResult]); | ||
return; | ||
} | ||
|
||
if (currentIndex === candidates.length) { | ||
return; | ||
} | ||
|
||
const candidate = candidates[currentIndex]; | ||
subResult.push(candidate); | ||
dfs(subResult, total + candidate, currentIndex); | ||
subResult.pop(); | ||
dfs(subResult, total, currentIndex + 1); | ||
} | ||
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
// 좌->우 방향의 누적곱과 우->좌 방향의 누적곱 활용 | ||
// TC: O(N) | ||
// SC: O(N) (답안을 제외하면 O(1)) | ||
|
||
/** | ||
* @param {number[]} nums | ||
* @return {number[]} | ||
*/ | ||
var productExceptSelf = function (nums) { | ||
const result = new Array(nums.length).fill(1); | ||
|
||
let leftToRight = 1; | ||
for (let index = 1; index < nums.length; index++) { | ||
leftToRight *= nums[index - 1]; | ||
result[index] *= leftToRight; | ||
} | ||
|
||
let rightToLeft = 1; | ||
for (let index = nums.length - 2; index >= 0; index--) { | ||
rightToLeft *= nums[index + 1]; | ||
result[index] *= rightToLeft; | ||
} | ||
|
||
return result; | ||
}; | ||
|
||
// 1차 풀이 | ||
// 0의 갯수가 0개, 1개, 2개인 경우로 나눠서 풀이 | ||
// 0개인 경우, 답안 배열의 원소는 '모든 원소 곱 / 현재 원소' | ||
// 1개인 경우, 0의 위치한 원소만 '0을 제외한 모든 원소 곱' 이고 그 외 '0' | ||
// 2개인 경우, 답안 배열의 모든 원소가 '0' | ||
|
||
// TC: O(N) | ||
// SC: O(N) | ||
|
||
/** | ||
* @param {number[]} nums | ||
* @return {number[]} | ||
*/ | ||
var productExceptSelf = function (nums) { | ||
const zeroCount = nums.filter((num) => num === 0).length; | ||
if (zeroCount > 1) { | ||
return new Array(nums.length).fill(0); | ||
} | ||
|
||
const multipled = nums.reduce( | ||
(total, current) => (current === 0 ? total : total * current), | ||
1 | ||
); | ||
|
||
if (zeroCount === 1) { | ||
const zeroIndex = nums.findIndex((num) => num === 0); | ||
const result = new Array(nums.length).fill(0); | ||
result[zeroIndex] = multipled; | ||
return result; | ||
} | ||
|
||
return nums.map((num) => multipled / num); | ||
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
// 2차: index를 값으로 갖는 Map을 활용하여 한번의 순회로 답안 도출 | ||
// TC: O(N) | ||
// SC: O(N) | ||
|
||
/** | ||
* @param {number[]} nums | ||
* @param {number} target | ||
* @return {number[]} | ||
*/ | ||
var twoSum = function (nums, target) { | ||
const valueIndexMap = new Map(); | ||
|
||
for (let index = 0; index < nums.length; index++) { | ||
const value = nums[index]; | ||
const anotherValue = target - value; | ||
|
||
if (valueIndexMap.has(anotherValue)) { | ||
return [index, valueIndexMap.get(anotherValue)]; | ||
} | ||
|
||
valueIndexMap.set(value, index); | ||
} | ||
}; | ||
|
||
// 1차: 정렬 후 투포인터 활용 | ||
// TC: O(N * logN) | ||
// SC: O(N) | ||
|
||
/** | ||
* @param {number[]} nums | ||
* @param {number} target | ||
* @return {number[]} | ||
*/ | ||
var twoSum = function (nums, target) { | ||
const sortedNums = nums | ||
.map((value, index) => ({ value, index })) | ||
.sort((a, b) => a.value - b.value); | ||
let left = 0; | ||
let right = sortedNums.length - 1; | ||
|
||
while (left < right) { | ||
const sum = sortedNums[left].value + sortedNums[right].value; | ||
if (sum < target) { | ||
left += 1; | ||
} else if (sum > target) { | ||
right -= 1; | ||
} else { | ||
return [sortedNums[left].index, sortedNums[right].index]; | ||
} | ||
} | ||
}; |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
공간 복잡도를 줄일 수 있는 좋은 풀이네요! 고생하셨습니다~