38. Count and Say / Medium / JavaScript #51
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.
설명
재귀
문제에서 설명하듯
countAndsay(n)
은countAndSay(n-1)
의 리턴값을 input으로 받아서특정한 방식으로 읽은 다음
그걸 output으로 내놓아야 함
즉 재귀를 사용함
재귀 탈출 조건은 'n=1'일 때 outout 이 1'이라는 것
"특정한 방식으로 읽은 것을 output으로"
"1211"을 count of num의 형식으로 읽는다고 하면
같은 숫자(
num
)가 몇 개가 나오는지를 카운트(count
)한 다음output 문자열에
${count}${num}
을 붙여주면 됨Time Complexity: O(1) to O(3410)
n의 범위는
1 <= n <= 30
n이 늘어남에 따라 return value의 길이는 아래와 같이 변함
[1, 2, 2, 4, 6, 6, 8, 10, 14, 20, 26, 34, 46, 62, 78, 102, 134, 176, 226, 302, 408, 528, 678, 904, 1182, 1540, 2012, 2606, 3410, 4462]
countAndsay(n)
은countAndSay(n-1)
의 리턴값을 순회하므로countAndSay(n-1)
의 리턴값의 길이만큼 연산을 수행함즉 Time Complexity의 최솟값은 O(1), 최댓값은 O(3410)
Space Complexity: O(1)
리턴할 문자열을 저장하는 용도의 변수 외에는 따로 공간을 요하는 것이 없음