완전탐색
카펫
def solution(brown, yellow):
answer = []
tmp = []
total = brown + yellow
for i in range(1, total):
if i * ((brown + 4)/2-i) == total :
tmp.append(i)
width = max(tmp)
length = min(tmp)
answer.append(width)
answer.append(length)
return answer
전체 카펫의 개수 : total = brown + yellow
total = 가로 길이 X 세로 길이
brown = ( 가로 길이 + 세로 길이 ) X 2 - 4
식을 적어보고 방정식st로 풀었다.
가로의 길이가 세로보다 길다고 했으니 max, min 함수를 이용했다.
def solution(brown, yellow):
# 전체 타일 수
total = brown + yellow
# (width + height)의 값을 계산합니다.
sum_width_height = (brown + 4) // 2
# 가능한 가로와 세로 길이를 찾습니다.
for height in range(1, int(total ** 0.5) + 1):
if total % height == 0:
width = total // height
if width >= height and width + height == sum_width_height:
return [width, height]
return []
int(total ** 0.5)
: 이거 사용한점이 천재 같다.. 굳이 total 전체 훑을 필요 없으니까..!
if width >= height and width + height == sum_width_height:
: 그리고 width가 height보다 커야 하니까!
import java.util.List;
import java.util.ArrayList;
class Solution {
public int[] solution(int brown, int yellow) {
List<Integer> answerList = new ArrayList<>();
int width = 0;
int total = brown + yellow;
int sum_width_height = (brown+4)/2;
for (int height = 1; height < Math.sqrt(total) + 1; height++) {
if ( total % height == 0 ) {
width = total / height;
if ( width >= height & width + height == sum_width_height ) {
answerList.add(width);
answerList.add(height);
}
}
}
int[] answer = new int[answerList.size()];
for (int i = 0; i < answer.length; i++) {
answer[i] = answerList.get(i);
}
return answer;
}
}
class Solution {
public int[] solution(int brown, int yellow) {
int[] answer = new int[2]; // Initialize the array with size 2
int width = 0;
int total = brown + yellow;
int sum_width_height = (brown + 4) / 2;
for (int height = 1; height <= Math.sqrt(total); height++) {
if (total % height == 0) {
width = total / height;
if (width >= height && width + height == sum_width_height) {
answer[0] = width;
answer[1] = height;
break; // Once the answer is found, break out of the loop
}
}
}
return answer;
}
}
answerList 사용할 필요 없이 바로 size 2로 초기화 해서 answer 배열에 담아주면 된다..! 배열의 길이가 정해져 있으니까!!