2010年中興面試題
編程求解:
輸入兩個整數 n 和 m,從數列1,2,3.......n 中 隨意取幾個數,
使其和等於 m ,要求將其中所有的可能組合列出來.
看了一下網絡上基本都是C++的答案,這和中興招人的要求有關,不過我是學java的,給一個java的算法:
主要思路是排列組合,然後把組合中符合條件的都過濾出來:
public class CombinationToSum {
public static void main(String[] args) {
permutation(6, 6);
}
private static void permutation(int sum, int n) {
for(int i=n; i>0; i--){
if(i == sum){
System.out.println(i);
continue;
}
int pos = i - 1;
while(pos > 0){
List<Integer> ls = new ArrayList<Integer>();
ls.add(i);
for(int j=pos; j>0; j--){
int ret = judge(ls, j, sum);
if(ret < 0){
ls.add(j);
}
if(ret == 0){
ls.add(j);
for(int k=0; k<ls.size(); k++){
System.out.print(ls.get(k) + " ");
}
System.out.println();
pos = ls.get(1) - 1;
break;
}
pos = 0;
}
}
}
}
private static int judge(List<Integer> ls, int num, int sum){
int result = 0;
int total = 0;
for(Integer i: ls){
total += i;
}
total += num;
if(total > sum){
result = 1;
}
if(total < sum){
result = -1;
}
return result;
}
}
輸入6, 6
輸出:
6
5 1
4 2
3 2 1
輸入10, 10
輸出:
10
9 1
8 2
7 3
7 2 1
6 4
6 3 1
5 4 1
5 3 2
4 3 2 1
大家可以試一下,如果以前沒有做過排列組合,中興出的題還是挺有難度的。