算法之美-回溯法组合问题

算法之美-回溯法组合问题

给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。

示例:

输入: n = 4, k = 2
输出:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

实现

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class Combinations {
	static List<List<Integer>> res;
public static void main(String[] args) {
	res = new ArrayList<>();
	int n = 4;
	int k = 2;
	if(n<=0||k<=0||k>n) {
		System.out.println("");
	}
	
	LinkedList<Integer> c = new LinkedList<>();
	generateCombinations(n,k,1,c);
	
	System.out.println(res.toString());
	
}
private static void generateCombinations(int n, int k, int start, LinkedList<Integer> c) {
	// TODO Auto-generated method stub
	if(c.size()==k) {
		res.add((List<Integer>) c.clone());
		return;
	}
	for(int i=start;i<=n;i++) {
		c.add(i);
		generateCombinations(n,k,i+1,c);
		c.removeLast();
	}
	return;
}
}

猜你喜欢

转载自blog.csdn.net/qq_35029061/article/details/91345730
今日推荐