发表时间:2007-08-15
最后修改:2009-02-25
描述:1,2,3......n 从n中取出r个数。
例如:n=5,r=3
1-2-3,1-2-4,1-2-5,1-3-4,1-3-5,1-4-5
2-3-4,2-3-5,2-4-5
3-4-5
下面是我的解决方法,还有其他的方法么?
java 代码
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.HashSet;
- import java.util.Iterator;
- import java.util.List;
- import java.util.Set;
- import java.util.Stack;
-
- public class Combination {
- private List result;
- private int r = 4;
- private int n = 7;
-
- public Combination() {
- result = new ArrayList();
- Stack permutation = new Stack();
- for (int i = 1; i < r + 1; i++) {
- permutation.push(i);
- }
- result.add(permutation);
- }
-
- public static void main(String[] args) {
- Combination com = new Combination();
- com.compose(com.result.size());
- com.removeExisted();
- com.sortList();
- com.print();
- }
-
- private void sortList() {
- List sorted = new ArrayList();
- for (Iterator iter = result.iterator(); iter.hasNext();) {
- Stack element = (Stack) iter.next();
- StringBuffer sb = new StringBuffer();
- for (Iterator iterator = element.iterator(); iterator.hasNext();) {
- int i = (Integer) iterator.next();
- sb.append(i + "-");
- }
- sb.deleteCharAt(sb.length()-1);
- sorted.add(sb.toString());
- }
- Collections.sort(sorted);
- result=sorted;
- }
-
- private void removeExisted() {
- Set set = new HashSet();
- for (Iterator iter = result.iterator(); iter.hasNext();) {
- set.add(iter.next());
- }
- result.clear();
- result.addAll(set);
- }
-
- private void print() {
- System.out.println("result:");
- for (Iterator iter = result.iterator(); iter.hasNext();) {
- String element = (String) iter.next();
- System.out.println(element);
- }
- }
-
- private void compose(int size) {
- for (int i = 0; i < size; i++) {
- Stack element = (Stack) result.get(i);
- int max = (Integer) element.peek();
- if (max == n) {
- return;
- } else {
- Stack copyedS = copyStack(element);
- ++max;
- createNewComS(copyedS, max);
- }
- }
- compose(result.size());
- }
-
- private void createNewComS(Stack original, int max) {
- for (int i = 0; i < r; i++) {
- Stack copyedS = copyStack(original);
- copyedS.remove(i);
- copyedS.push(max);
- result.add(copyedS);
- }
- }
-
- private Stack copyStack(Stack element) {
- Stack copyed = new Stack();
- for (int i = 0; i < element.size(); i++) {
- int num = (Integer) element.get(i);
- copyed.push(num);
- }
- return copyed;
- }
- }