-
Notifications
You must be signed in to change notification settings - Fork 0
4-sep037 #21
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
Conversation
| //var array = [Int](repeating: 0, count: N + 1) | ||
| // 처음에 생각 안 하고 N개 만들었다가 N에 2나 1 같은 게 들어올 수 있는 걸 대응 안 했다. | ||
| // 만약 1이 들어왔을 경우 아래 초기화는 bound를 넘어서게 된다. 그렇다면 최소 배열을 4로 만들어주면 됨 ! | ||
| var array = [Int](repeating: 0, count: max(N + 1, 4)) |
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.
저도 처음에 count : N + 1로 했다가 런타임에러에 당했네요..!
max로 최소배열 해주는거 신선하네요! 👍 저도 다음번에 써먹겠습니다.
이 문제는 최대 N이 11 밖에 안돼서 count:12로 해주는것도 좋은 것 같아요!
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.
저는 var dp = Array(repeating: 0, count: N + 1)으로 다행히? 런타임을 피했네요 ㄷㄷㄷ
| array[2] = 2 | ||
| array[3] = 4 // 3까지는 자기 자신을 가지고 있기 때문에 초기화 해줘야 함 | ||
|
|
||
| if N >= 4 { // 여기도 마찬가지로 N이 4이상인 경우로 제한해줘야 한다. |
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.
이럴때 guard같은거로 제한두시면 바로 반복문도 시작할 수 있고 더 좋을 것 같아요!
저도 익숙하지 않아서 억지로라도 써보려구요..! 👍
guard n > 3 else {
print(arr[n])
return
}
for i in 4 ... n {
arr[i] = arr[i-1] + arr[i-2] + arr[i-3]
}
bishoe01
left a comment
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.
코드 구조는 거의 동일한 것 같아요..!
주석으로 풀이 흔적들 남겨주시니까 흐름이 보여서 좋네요 ~ 잘 풀었습니다
func solution(_ n: Int) {
var arr = [Int](repeating: 1, count: 12)
arr[1] = 1
arr[2] = 2
arr[3] = 4
guard n > 3 else {
print(arr[n])
return
}
for i in 4 ... n {
arr[i] = arr[i-1] + arr[i-2] + arr[i-3]
}
print(arr[n])
}
YooGyeongMo
left a comment
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.
글로리 ~ 글로리 ~ 어쩌면 ADA의 초고수 일수도 ?
| //var array = [Int](repeating: 0, count: N + 1) | ||
| // 처음에 생각 안 하고 N개 만들었다가 N에 2나 1 같은 게 들어올 수 있는 걸 대응 안 했다. | ||
| // 만약 1이 들어왔을 경우 아래 초기화는 bound를 넘어서게 된다. 그렇다면 최소 배열을 4로 만들어주면 됨 ! | ||
| var array = [Int](repeating: 0, count: max(N + 1, 4)) | ||
|
|
||
| array[1] = 1 | ||
| array[2] = 2 | ||
| array[3] = 4 // 3까지는 자기 자신을 가지고 있기 때문에 초기화 해줘야 함 |
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.
저는 보통 DP나 배열의 0-based index 혹은 1-based index 할때 입력값의 제한을 보는 편인데, 저는 그냥 바로 1~10까지만 나오면 되겠다라고 생각을 했습니다.
그래서 모든배열을 그냥 한번에 초기화하고 원하는 조건을 뱉어주자 dp + 약간 해싱 느낌으로 접근한거같아요.
func solution() {
let testCase = Int(readLine()!)!
var dp = Array(repeating:0, count:11)
dp[1] = 1
dp[2] = 2
dp[3] = 4
for i in 4..<11 {
dp[i] = dp[i-1] + dp[i-2] + dp[i-3]
}
글로리의 코드는 저의 코드에 비해서 유동성이 확실히 좋다고 판단했습니다. 확실한 초기화값 초기값을 바로 뱉어주기 위해서 1,2,3 먼저 배열에 넣고 추후에 추가되는 값들을 인덱싱으로 넣어주는 판단을하셨는데 너무 좋은거같아요.
이 문제에서는 글로리의 입력 출력방식이 더 문제에 최적화되어있었던것같습니다 ! 아주 좋은 코드네요 !
| if N >= 4 { // 여기도 마찬가지로 N이 4이상인 경우로 제한해줘야 한다. | ||
| for i in 4 ... N { | ||
| array[i] = array[i - 1] + array[i - 2] + array[i - 3] | ||
| } | ||
| } | ||
|
|
||
| return array[N] | ||
| } | ||
|
|
||
| for k in number { | ||
| print(dp(N : k)) | ||
| } | ||
|
|
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.
글로리도 숨겨진 ADA의 고수일 수도 함수 나누는게 너무 보기좋아요. 성능에 신경쓴 코드입니다. 캐싱 해싱 구조 띄고있으나, 추후에 입력을 strict하게 준다면 저는 아마도 틀린 코드이지 않을가 싶네요.
import Foundation
func solution() {
let testCase = Int(readLine()!)!
var dp = Array(repeating:0, count:11)
dp[1] = 1
dp[2] = 2
dp[3] = 4
for i in 4..<11 {
dp[i] = dp[i-1] + dp[i-2] + dp[i-3]
}
for _ in 0..<testCase {
let n = Int(readLine()!)!
print(dp[n])
}
}
solution()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.
@YooGyeongMo 입력 값 max 11둔거 칼같이 캐치하고 적용하신거 보고 저도 문제 좀 제대로 읽어야겠다는 생각을 했습니다. 고마워요!
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.
일단 저에게 dp 자신감을 심어준 글로니에게 감사의 인사드리고 시작하겠습니다.^^ (기초 디피 문제 조아)
나름 규칙을 찾았고 점화식도 도출한 뒤 코드로 옮겼습니다. 그리고 나 쫌 하는데??^^ 싶었으나.....
님들 코드보니까 다시 반성하게 되네요.
일단 성능을 조금 더 고민하지 않음. DP를 풀었다는 기쁨에 취해.
1.2.3 값을 두고 4부터 반복문 돌렸으면 됐었네요. hmm..
그리고 데미안보니 입력 값에서 최대 입력값도 고려해서 짜신 것 보고 저도 문제를 조금 더 자세히 봐야겠다는 생각이 들었습니다..^^
import Foundation
let T = Int(readLine()!)!
for _ in 1...T {
let n = Int(readLine()!)!
var dp = Array(repeating: 0, count: n+1)
for i in 1...n {
if i == 1 { dp[i] = 1 }
else if i == 2 { dp[i] = 2 }
else if i == 3 { dp[i] = 4 }
else {
dp[i] = dp[i-1] + dp[i-2] + dp[i-3]
}
}
print(dp[n])
}| //var array = [Int](repeating: 0, count: N + 1) | ||
| // 처음에 생각 안 하고 N개 만들었다가 N에 2나 1 같은 게 들어올 수 있는 걸 대응 안 했다. | ||
| // 만약 1이 들어왔을 경우 아래 초기화는 bound를 넘어서게 된다. 그렇다면 최소 배열을 4로 만들어주면 됨 ! | ||
| var array = [Int](repeating: 0, count: max(N + 1, 4)) |
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.
오우 마카로니.... 고수다.... 응용하기 좋은 코드네요.
| array[1] = 1 | ||
| array[2] = 2 | ||
| array[3] = 4 // 3까지는 자기 자신을 가지고 있기 때문에 초기화 해줘야 함 |
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.
이렇게 따로 빼두셨군요. 전 다 1부터 다 돌렸는데.. 전 아직 멀었습니다.
| var number : [Int] = [] | ||
|
|
||
| for _ in 0 ..< N { | ||
| number.append(Int(readLine()!)!) | ||
| } |
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.
궁금한점이 두가지가 있어요.
- 따로 number 배열을 둔 이유가 있을까요? + 배열 네이밍은 's'를 뒤에 붙여주는게 관행이옵니다.
- 어떨 땐 배열을
var number = [Int]()로 선언하시고 이번엔var number: [Int] = []와 같이 선언하셨는데 기준이 있나요?
| if N >= 4 { // 여기도 마찬가지로 N이 4이상인 경우로 제한해줘야 한다. | ||
| for i in 4 ... N { | ||
| array[i] = array[i - 1] + array[i - 2] + array[i - 3] | ||
| } | ||
| } | ||
|
|
||
| return array[N] | ||
| } | ||
|
|
||
| for k in number { | ||
| print(dp(N : k)) | ||
| } | ||
|
|
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.
@YooGyeongMo 입력 값 max 11둔거 칼같이 캐치하고 적용하신거 보고 저도 문제 좀 제대로 읽어야겠다는 생각을 했습니다. 고마워요!
giljihun
left a comment
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.
이전에 제가 풀었던 동전1 문제가 생각나서
빠른 접근이 가능했습니다.
import Foundation
guard let T = Int(readLine() ?? "") else { exit(0) }
var answer = [Int]()
(0..<T).forEach { _ in
guard let n = Int(readLine() ?? "") else { exit(0) }
if n == 1 {
answer.append(1)
return
}
if n == 2 {
answer.append(2)
return
}
if n == 3 {
answer.append(4)
return
}
var dp = [Int](repeating: 0, count: n + 1)
dp[0] = 1
dp[1] = 1
dp[2] = 2
for i in 3...n {
dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3]
}
answer.append(dp[n])
}
(0..<T).forEach { print(answer[$0]) }그래서 그런지 이번문제는 디버깅을 크게 고려하지않고
쭉쭉 라인타고 내려오듯이 코드를 작성했습니다!
dp는 숫자 1부터 1, 2, 3을 가지고 만들 수 있는 경우의 수를 구하는 방식으로 구했습니다.
| // 처음에 생각 안 하고 N개 만들었다가 N에 2나 1 같은 게 들어올 수 있는 걸 대응 안 했다. | ||
| // 만약 1이 들어왔을 경우 아래 초기화는 bound를 넘어서게 된다. 그렇다면 최소 배열을 4로 만들어주면 됨 ! |
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.
런타임오류에 대한 처리를 잘하셨네요.
저는 아래처럼 단순하게 해서 시작했어요~
if n == 1 {
answer.append(1)
return
}
if n == 2 {
answer.append(2)
return
}
if n == 3 {
answer.append(4)
return
}
alstjr7437
left a comment
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.
오호 다들 1,2,3 부분은 그냥 상수값을 두셨군요 저는
0부터 값을 넣어주고 그 값이 더할 수 있을때만 3개를 더하도록 했습니다
for _ in 0..<Int(readLine()!)! {
let N = Int(readLine()!)!
var dp = Array(repeating: 0, count: N + 1)
dp[0] = 1
for i in 1..<N + 1{
if i >= 1 {
dp[i] += dp[i - 1]
}
if i >= 2 {
dp[i] += dp[i - 2]
}
if i >= 3 {
dp[i] += dp[i - 3]
}
}
print(dp[N])
}|
|
||
| let N = Int(readLine()!)! | ||
|
|
||
| var number : [Int] = [] |
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.
문제에서는 T로 주어져서 했갈렸네요 ㄷㄷㄷㄷ
| //var array = [Int](repeating: 0, count: N + 1) | ||
| // 처음에 생각 안 하고 N개 만들었다가 N에 2나 1 같은 게 들어올 수 있는 걸 대응 안 했다. | ||
| // 만약 1이 들어왔을 경우 아래 초기화는 bound를 넘어서게 된다. 그렇다면 최소 배열을 4로 만들어주면 됨 ! | ||
| var array = [Int](repeating: 0, count: max(N + 1, 4)) |
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.
저는 var dp = Array(repeating: 0, count: N + 1)으로 다행히? 런타임을 피했네요 ㄷㄷㄷ
🔗 문제 링크
1, 2, 3 더하기
제가 직접 색칠함
4는 필요 없다 나가라
✔️ 소요된 시간
이런 문제를 많이 안 풀어봐서 dp로 푸는 건 알고 들어 갔는데
규칙 찾느라 한세월 ~ ..
✨ 수도 코드
직전의 숫자의 개수에서는 +1만 하면 되고,
2개 전 숫자의 개수에서는 +2만 하면 되고,
3개 전 숫자의 개수에서는 +3만 하면 됩니다 !
고로 구하고자 하는 수에서는 직전 3개 숫자의 개수를 모두 더하면 되는 것 !
📚 새롭게 알게된 내용
처음에 테스트케이스 값이 작을 수 있다는 사실을 고려하지 않고 코드를 짰다 !
그래서 lowbound 문제가 있었고 . .
입력 받는 N의 값에 따라 배열의 크기를 정하게 되면 초기화시 index를 벗어나게 되는데 이것도 고려하지 않았고 !
그래서 배열 크기를 최소 4 이상으로 고정했습니다 ㅠ
초기 조건을 하드 코딩 하는 경우에 그 조건이 안전하게 실행될 수 있는 메모리 범위를 확보해야 한다는 점을 깨달았습니다 ~ 🥹
DP 이론을 공부하면서 Top - Down 방식과 Bottom - Up 방식 나누어서 공부를 해봤어요.
Top - Down 방식
큰 문제를 풀기 위해 작은 문제를 재귀적으로 호출합니다.
이미 계산한 값은 저장해두고, 다시 계산하지 않습니다.
재귀 함수 안에서 메모이제이션을 사용하는 방식입니다.
Bottom - Up 방식
가장 작은 하위 문제부터 차근차근 결과를 구해서 결과를 쌓아올립니다.
배열 등을 사용하여, 작은 문제의 해답을 저장하고 큰 문제로 확장시켜요.
이번 문제는 바로 Bottom-Up으로 접근해서 풀긴 했는데
아직 문제마다 바로 바로 나오는 감은 없는 것 같아요 . . 네 많이 풀어보겠습니다
고럼 이만 !