日期:2014-05-20 浏览次数:20740 次
import java.util.ArrayList; class Combination { ArrayList<ArrayList> _E = new ArrayList<ArrayList>(); int _n; int _k; Combination(int n, int k) { _n = n; _k = k; if (_k > _n || _k < 0 || _n < 0) { _n = 0; _k = 0; } int temp[] = new int[_k]; Permutation _p = new Permutation(_n, _k); for (int i = 0; i < _p.getSize(); ++i) { _p.getElements(i, temp); if (isUniqueElement(temp) == true) { ArrayList<Integer> Nums = new ArrayList<Integer>(); for (int j = 0; j < _k; ++j) { Nums.add(temp[j]); } _E.add(Nums); } } } public int getN() { return _n; } public int getK() { return _k; } public void getElements(int count, int val[]) { ArrayList<Integer> temp = new ArrayList<Integer>(); if (count < getSize()) { temp = _E.get(count); for (int i = 0; i < temp.size(); ++i) { val[i] = temp.get(i); } } } public String toString(int count) { ArrayList<Integer> temp = new ArrayList<Integer>(); temp = _E.get(count); String result = ""; for (int i = 0; i < _k; ++i) { result += (temp.get(i) + 1); if (i != _k - 1) result += ","; } return result; } public long getSize() { long size = 0; size = factorial(_n) / factorial(_n - _k) / factorial(_k); return size; } private long factorial(int n) { if (n == 0) { return 1; } else { return n * factorial(n - 1); } } private boolean isUniqueElement(int val[]) { java.util.Arrays.sort(val); int temp[] = new int[_k]; for (int i = 0; i < _E.size(); ++i) { getElements(i, temp); java.util.Arrays.sort(temp); boolean match = true; for (int j = 0; j < temp.length; ++j) { if (val[j] != temp[j]) { match = false; break;// ほんのちょっと時間節約 } } if (match == true) return false; } return true; }