따라서 주어진 s를 n으로 나눠 크기가 n인 배열을 만들었고, 나머지는 각 원소에 1씩 값을 더하여 배열을 구성했다.
더하는 작업을 끝 인덱스부터 했기에 불가능한 경우의 수는 answer[0]의 값이 0인지를 확인하여 반환했다.
C/C++ 코드
#include <string>
#include <vector>
using namespace std;
vector<int> solution(int n, int s) {
// s / n 을 원소로 가진 크기가 n인 집합 생성
int div = s / n;
vector<int> answer(n, s / n);
// 나머지가 없다면 바로 리턴
if (s % n == 0)
return answer;
// 나머지만큼의 원소 갯수에 각각 1씩 더함
else {
int rem = s - s / n * n;
int idx = n - 1;
while (rem--)
answer[idx--]++;
}
// 0번째 인덱스에 값이 있다면 answer 반환
if (answer[0])
return answer;
return {-1};
}
Java 코드
import java.util.*;
class Solution {
public int[] solution(int n, int s) {
// s / n 을 원소로 가진 크기가 n인 집합 생성
int[] answer = new int[n];
Arrays.fill(answer, s / n);
int remain = s - s / n * n;
int idx = n - 1;
// 나머지가 있다면 원소당 1씩 추가해 나머지를 채움
while (remain-- > 0)
answer[idx--]++;
// 첫번째 원소가 0이라면 s를 만들 수 없으므로 -1 반환
if (answer[0] == 0)
return new int[] {-1};
return answer;
}
}