Skip to content

[재호] 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 9 commits into from
Sep 1, 2024
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
21 changes: 21 additions & 0 deletions climbing-stairs/wogha95.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// DP 활용하였고 메모리 축소를 위해 현재와 직전의 경우의 수만 관리하였습니다.
// TC: O(N)
// SC: O(1)
Copy link
Contributor

Choose a reason for hiding this comment

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

공간 복잡도를 줄일 수 있는 좋은 풀이네요! 고생하셨습니다~


/**
* @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;
};
23 changes: 23 additions & 0 deletions coin-change/wogha95.js
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];
};
84 changes: 84 additions & 0 deletions combination-sum/wogha95.js
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)
Copy link
Member

Choose a reason for hiding this comment

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

시간 복잡도를 어떻게 O(C^T)로 분석하셨을까요? dfs() 함수 내에서 재귀 호출이 2번씩 일어나는 것 같아서 여쭙니다.

Copy link
Contributor Author

@wogha95 wogha95 Aug 31, 2024

Choose a reason for hiding this comment

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

@DaleSeo

앗, 제가 잘못 분석했습니다!
문제 풀고 알고달레 풀이 확인하면서 머리 속에 알고달레 풀이로 기억해버렸나봅니다..

다시 수정해서 TC: O(2^C)로 분석했는데 한번 확인 부탁드려도 될까요.?
(C: candidates.length)


모임에서 의견 주셔서 다시 생각해볼 수 있었습니다!
복잡도의 밑은 이해가 되지만 지수가 직관적으로 이해되지 않아서 고민해봐야겠습니다..

// 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);
}
};
59 changes: 59 additions & 0 deletions product-of-array-except-self/wogha95.js
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);
};
51 changes: 51 additions & 0 deletions two-sum/wogha95.js
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];
}
}
};