日期:2014-05-20 浏览次数:20855 次
public class Test { public static void main(String[] args) { int[] arr = new int[] { 1, 3, 5, 7, 9 }; get(arr, 2); } public static void get(int[] a, int n) { if (n > a.length || n == 0) { return; } for (int i = n - 1; i < a.length; i++) { for (int j = 0; j < n - 1; j++) { System.out.print(a[j] + " "); } System.out.print(a[i] + "\n"); } if (a.length - 1 < n || n == 1) { return; } int[] b = new int[a.length - 1]; for (int i = 0; i < b.length; i++) { if (i == 0 && n != 2) { b[i] = a[i]; } else { b[i] = a[i + 1]; } } get(b, n); } }
------解决方案--------------------
import java.util.Random; public class Combination{ int[] array={1,2,3}; MyLinkedList newArray; boolean[] flags; int Cishu = 2; public Combination(int number){ flags = new boolean[array.length]; for(int i=0;i<array.length;i++){ flags[i] = false;//表示该元素未取出 } newArray = new MyLinkedList(); this.Cishu = number; } public Combination(int[] array,int number){ this.array = array; flags = new boolean[array.length]; for(int i=0;i<array.length;i++){ flags[i] = false;//表示该元素未取出 } newArray = new MyLinkedList(); this.Cishu = number; } public void getElement(){ Random rd = new Random(); int number = Math.abs(rd.nextInt()%array.length); while(flags[number]){//如果该数已经取出来了,丢弃,重取 number = Math.abs(rd.nextInt()%array.length); } newArray.addElement(array[number]); flags[number] = true; } public void print(){ for(int i=0;i<Cishu;i++){ getElement(); } Node node = newArray.head; while(node!=null){ System.out.print(node.in+"|"); node = node.next; } } public static void main(String args[]){ new Combination(2).print(); } } class MyLinkedList{ Node head; Node tail; public void addElement(Integer in){ if(head==null){ Node node = new Node(in); head = node; tail = node; return; } if(head.in > in){ Node node = new Node(in); head.prev = node; node.next = head; head = node; return; } Node zhizhen = head.next; while(zhizhen != null){ if(zhizhen.in > in){//从小到大排序。 Node node = new Node(in); zhizhen.prev.next = node; node.prev = zhizhen.prev; node.next = zhizhen; zhizhen.prev = node; return; } zhizhen = zhizhen.next; } Node node = new Node(in);//循环都没找到,说明是最大的 tail.next = node; node.prev = tail; tail = node; } } class Node{// Integer in; Node next =null;//后向指针 Node prev = null;//前向指针 public Node(){ } public Node(Integer in){ this.in = in; this.next=null; this.prev=null; } }
------解决方案--------------------
for example
public class Test { public static void main(String[] args) { combine(new int[]{1,2,3,4,5}, 3); } public static void combine(int[] a, int n) { if (n > a.length) { for (int i : a) { System.out.printf("%d ", i); } return; } int idx=0, t=0, p=(int)Math.pow(2, a.length); while (p > 0) { if (Integer.bitCount(p) == n) { t = p; idx = 0; while (t > 0) { if (t%2==1) { System.out.printf("%d ", a[idx]); } t >>= 1; idx++; } System.out.println(); } p--; } } }