java 多个数 组合成不同的组
public static Stack<Integer> stack = new Stack<Integer>(); private static List<String> listint = new ArrayList<String>(); public static void main(String[] args) { int nums[] = { 1, 2, 3, 4 }; for (int i = 2; i <= nums.length; i++) { groupData(nums, i, 0); } } private static void groupData(int[] nums, int targ, int cur) { // TODO Auto-generated method stub if (cur == targ) { Object[] shu1 = stack.toArray(); Arrays.sort(shu1); if (!listint.contains(Arrays.toString(shu1))) { System.out.println(Arrays.toString(shu1)); } listint.add(Arrays.toString(shu1)); return; } for (int i = 0; i < nums.length; i++) { if (stack.contains(nums[i])) { continue; } stack.add(nums[i]); groupData(nums, targ, cur + 1); stack.pop(); } }
输出:
[1, 2]
[1, 3]
[1, 4]
[2, 3]
[2, 4]
[3, 4]
[1, 2, 3]
[1, 2, 4]
[1, 3, 4]
[2, 3, 4]
[1, 2, 3, 4]