JAVA算法:给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合(JAVA)
给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。、
当 n = 4 ,k = 2 时;
结果为: [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
算法设计
package com.bean.algorithmbasic;
import java.util.LinkedList;
import java.util.List;
public class CombinationsDemo5 {
/*
* n = 4 and k = 2
* 结果: [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
*
*/
// 全局变量,存储返回结果
private List<List<Integer>> ret = new LinkedList<List<Integer>>();
public List<List<Integer>> combine(int n, int k) {
// 非法条件:一旦出现以下条件,直接返回空
if (n <= 0 || k <= 0 || k > n)
return ret;
// 初始化一个可能结果c,当前c为空;c中存储一个可能的组合结果(c这个链表在整个过程是会变的)
LinkedList<Integer> c = new LinkedList<Integer>();
/