하나의 정수를 약간의 정수의 합으로 나누어 각각의 구분 방법을 출력하다
1206 단어 면접 문제
import java.util.ArrayList;
// ( max) ,
public class IntDivision {
// n , max
public static ArrayList> divideInt_r(int n, int max){
ArrayList> divisionList = new ArrayList>();
if(n <= 1){
ArrayList list = new ArrayList();
if(n==1) list.add(1);
divisionList.add(list);
return divisionList;
}
for(int i=max; i>0; i--){
ArrayList> newDivList = divideInt_r(n-i, Math.min(n-i, i));//sublist i, n-i
for(ArrayList sublist : newDivList){
sublist.add(0, i);
divisionList.add(sublist);
}
}
return divisionList;
}
public static void main(String[] args){
ArrayList> divisionList = divideInt_r(6,4);
System.out.println("Total divisions: "+divisionList.size());
for(ArrayList list : divisionList){
for(Integer num : list){
System.out.print(num+" ");
}
System.out.println();
}
}
}
Total divisions: 9
4 2
4 1 1
3 3
3 2 1
3 1 1 1
2 2 2
2 2 1 1
2 1 1 1 1
1 1 1 1 1 1