//组合问题(从M个不同字符中任取N个字符的所有组合)
static void combinationMN(){
int n = 3;
String source = "ABCDE";
char[] result = new char[n];
if (n > 0 && source.length() > 0 && n <= source.length())
find(source, result, n);
}
static void find(String source, char[] result, int n)
{
String temp="";
char[] arr = source.toCharArray();
if (n == 1)
{
int i = 0;
while (i < arr.length) {//进入这里 表明只剩最后一位没有确定
result[result.length - 1] = arr[i++];//如果是任意取一个元素 就等于是全部输出
System.out.println(new String(result));
}
}
else
{
int i = arr.length, j, k = 0;
for (j = 0; result[j] != 0; j++);
//将指针向后移动 直到移动至result[j]==0 表示指针此时在已有数据的最后面
//{x,x,x,x,x,x,0,0,0,0,0} 元素是一个一个在最后加上的 所以要找到末尾元素后第一个空位
//一开始 n=3 那么这里执行2次 n就是1 所以先去除了AB 然后剩余的是CDE
//组成了 ABC ABD ABE
//接下来是 AC 还剩DE
for (; i >= n; i--)
{
result[j] = arr[k++];//向result[]数组中添加数据
result[j + 1] = '/0';
temp=source.substring(k);
find(temp, result, n - 1);//substring(int k)截取k~end下标的字串
}
}
//组合问题(从M个不同字符中任取N个字符的所有组合)
最新推荐文章于 2024-02-17 23:06:17 发布