一道关于组合的问题,例如ABCD,他们有多少种组合,请你输出来,算法有两种。

一种是用Stack的方法,我是参考网上一个牛人的算法实现的。

另外一种,理解起来就容易好多。如:ABCD

其实就是1111(16进制)进行-1的操作,直到变成0000为止。每次减一时,将得到的数为1的值输出。如1111-1 = 1110,就是ABC的意思。

现在大家分别来看一下这两种代码怎样实现他们的思想吧.

第一种 :

package test;


import java.util.Stack;


public class Combination {
public static char[] array = {'A', 'B', 'C'};
private static Stack<Character> stack = new Stack<Character>();

public static void combination(int index) {
if (index > array.length-1) return;

stack.push(array[index]); 
print(stack);
combination(index + 1);
stack.pop(); 
combination(index + 1);
}

public static void print(Stack<Character> stack) {
for (Character i : stack) {
System.out.print(i + "  ");
}
System.out.println();
}


public static void main(String[] args) {
combination(0);
}
}

第二种:

package test;


public class Person {
public static void main(String[] s) {
char[] array = {'A', 'B', 'C'};
int n = array.length;
int total = (int) Math.pow(2, n);
for (int i = 1; i < total; i++) {
String result = "";
for (int j = 0; j < n; j++) {
if (((i >> j) % 2) == 1) {
result += array[j];
}
System.out.print(result);
result = "";
}
System.out.println();
}
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值