java递归 指定集合中元素的组合

打印集合中元素的组合

package arraystolist;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 选出所有组合
 * @author hanxiaofan
 *
 */
public class Combinations {
	
	/**
	 * @param selector	选完的集合 初始化为空
	 * @param list		待选集合
	 * @param n			选出的数量
	 */
	public void combinations(List selector,List data,int n) {
		
		if(n == 0) {
			for (Integer i : selector) {
				System.out.print(i);
		        System.out.print(" ");
			}
			System.out.println();
			return;
		}
		
		if(data.isEmpty()) {
			return;
		}
		
		//选择第一个元素,将元素放入集合
		selector.add(data.get(0));
		combinations(selector,data.subList(1, data.size()),n - 1); //从第二个元素开始选择,再选择两个
		
		//不选择第一个元素
		selector.remove(selector.size() -1 );
		combinations(selector,data.subList(1, data.size()), n); //从第二个元素开始选择,选择两个
		
	}
	
	public static void main(String[] args) {
		Combinations comb = new Combinations();	
	 	/*System.out.println("Testing normal data.");
	    comb.combinations(
	        new ArrayList<>(), Arrays.asList(1, 2, 3, 4), 2);
	    System.out.println("==========");*/
/*
	    System.out.println("Testing empty source data.");
	    comb.combinations(
	        new ArrayList<>(), new ArrayList<>(), 2);
	    System.out.println("==========");
	    comb.combinations(
	        new ArrayList<>(), new ArrayList<>(), 0);
	    System.out.println("==========");

	    System.out.println("Selecting 1 and 0 elements.");
	    comb.combinations(
	        new ArrayList<>(), Arrays.asList(1, 2, 3, 4), 1);
	    System.out.println("==========");
	    comb.combinations(
	        new ArrayList<>(), Arrays.asList(1, 2, 3, 4), 0);
	    System.out.println("==========");*/

	    System.out.println("Testing large data");
	    comb.combinations(
	        new ArrayList<>(),
	        Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), 4);
	}
}

你可能感兴趣的:(算法)