您的位置:首页 > 其它

数的组合问题,从n个数中选出m个数,结果按照字典序排列

2017-09-04 01:18 507 查看

数的组合问题,从n个数中选出m个数,结果按照字典序排列

数的组合问题。从1,2,…,n中取出m个数,将所有组合按照字典顺序列出。如n=3,m=2时,输出:12 13 23

思想:每个数的选择都有可能,比如选择两个数,假设第一个选择的是第i(i从0开始)个数,则剩下的就从i+1到length-1中选择。

实现如下:

import java.util.LinkedHashSet;

public class Combination {

static LinkedHashSet<String> lSet = new LinkedHashSet<>();
public static void Combination(int[] a, int count, String s)
{
if(count == 0){
lSet.add(s);
return;
}
for(int i = 0; i < a.length; i++){
int[] b = new int[a.length-(i+1)];
for(int j = 0; j < b.length; j++){
b[j] = a[j+i+1];
}
String s2 = s + a[i];
Combination(b, count - 1, s2);
}
}
public static void main(String[] args){

String s = new String();
int[] a = new int[]{1,2,3,4,5};
int count = 3;
Combination(a, count, s);
System.out.println(lSet.toString());
}
}
代码中的count表示要选的数的个数,s是每次选择出的结果。
结果如下:
[123, 124, 125, 134, 135, 145, 234, 235, 245, 345]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: