Last active
April 29, 2022 03:47
-
-
Save jihunleekr/acda40ef5307d6a1a57451f6fee2408b to your computer and use it in GitHub Desktop.
덧셈사슬 구하기
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
// 트리 노드 | |
function Node(value, parent = null) { | |
this.value = value; // 덧셈사슬을 구할 수 | |
this.parent = parent; // 부모 노드 | |
this.count = 0; // 최소덧셈 | |
} | |
function getAdditionChain(to = 99) { | |
const minCounts = new Array(to + 1).fill(to); | |
minCounts[0] = null; // 배열은 1부터 사용합니다. | |
const queue = []; | |
queue.push(new Node(1)); | |
while (queue.length > 0) { | |
const term1 = queue.shift(); | |
let term2 = term1; | |
if (term1.value > to) continue; | |
if (minCounts[term1.value] < term1.count) continue; | |
minCounts[term1.value] = term1.count; | |
while (true) { | |
const newNode = new Node(term1.value + term2.value, term1); | |
newNode.count = term1.count + 1; | |
queue.push(newNode); | |
if (term2.parent === null) break; | |
else term2 = term2.parent; | |
} | |
} | |
return minCounts; | |
} | |
console.table(getAdditionChain(99)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
브라우저 콘솔에 복붙하시면 됩니다.