아래와 같이 5와 사칙연산만으로 12를 표현할 수 있습니다.
12 = 5 + 5 + (5 / 5) + (5 / 5)
12 = 55 / 5 + 5 / 5
12 = (55 + 5) / 55를 사용한 횟수는 각각 6,5,4 입니다. 그리고 이중 가장 작은 경우는 4입니다.
이처럼 숫자 N과 number가 주어질 때, N과 사칙연산만 사용해서 표현 할 수 있는 방법 중 N 사용횟수의 최솟값을 return 하도록 solution 함수를 작성하세요.
N은 1 이상 9 이하입니다.
number는 1 이상 32,000 이하입니다.
수식에는 괄호와 사칙연산만 가능하며 나누기 연산에서 나머지는 무시합니다.
최솟값이 8보다 크면 -1을 return 합니다.
import java.util.*;
class Solution {
private int ret = 9;
private List<List<Integer>> nums;
public int solution(int N, int number) {
nums = new ArrayList<>();
// 0개는 그냥 보기 쉽도록 빈 list 넣어준다.
nums.add(new ArrayList<Integer>());
StringBuilder sb = new StringBuilder();
for(int i=1 ; i<=8 ; i++) {
nums.add(new ArrayList<Integer>());
sb.append(""+N);
int insert = Integer.valueOf(sb.toString());
if(insert==number) {
return i;
} else {
nums.get(i).add(insert);
}
}
for(int i=1 ; i<=7 ; i++) {
List<Integer> l1 = nums.get(i);
for(int j=1 ; i+j<=8 ; j++) {
List<Integer> l2 = nums.get(j);
helper(i,j);
if(nums.get(i+j).contains(number) && ret>i+j) ret = i+j;
}
}
return ret>8?-1:ret;
}
public void helper(int i, int j) {
List<Integer> l1 = nums.get(i);
List<Integer> l2 = nums.get(j);
for(int n1=0 ; n1<l1.size(); n1++) {
for(int n2=0 ; n2<l2.size(); n2++) {
int plus = l1.get(n1)+l2.get(n2);
int mul = l1.get(n1)*l2.get(n2);
int minus = Math.max(l1.get(n1),l2.get(n2))-Math.min(l1.get(n1),l2.get(n2));
int div = Math.max(l1.get(n1),l2.get(n2))/Math.min(l1.get(n1),l2.get(n2));
if(!nums.get(i+j).contains(plus)) nums.get(i+j).add(plus);
if(!nums.get(i+j).contains(mul)) nums.get(i+j).add(mul);
if(!nums.get(i+j).contains(minus)&& minus>0) nums.get(i+j).add(minus);
if(!nums.get(i+j).contains(div)&& div>0) nums.get(i+j).add(div);
}
}
return;
}
}
무려 4중 포문으로 돌리는거라 맞나 싶었다.