【leetcode】77.(Medium)Combinations

解题思路:
回溯


提交代码:

class Solution {
	public List<List<Integer>> combine(int n, int k) {
		List<List<Integer>> ans = new ArrayList<List<Integer>>();
		List<Integer> curComb = new ArrayList<Integer>();

		for (int i = 0; i < n; i++) {
			curComb.add(i+1);
			makeCombination(curComb, n, k, ans);
			curComb.remove(curComb.size()-1);
		}
		return ans;
	}

	public void makeCombination(List<Integer> curComb, int n, int k, List<List<Integer>> ans) {
		if (curComb.size() == k) {
			List<Integer> tmp=new ArrayList<Integer>();
			tmp.addAll(curComb);
			ans.add(tmp);
			return;
		}

		for (int i = curComb.get(curComb.size()-1); i < n; i++) {
			curComb.add(i+1);
			makeCombination(curComb, n, k, ans);
			curComb.remove(curComb.size()-1);
		}
	}

}

运行结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/AXIMI/article/details/84333793
今日推荐