Given two integers n and k, return all possible combinations of k numbers out of 1 … n.
Example:
Input: n = 4, k = 2Output:[[2,4],[3,4],[2,3],[1,2],[1,3],[1,4],]
题意
从n个数中选取k个组成集合,输出所有这样的集合。
思路
回溯法,注意剪枝。
代码实现
class Solution {public List<List<Integer>> combine(int n, int k) {List<List<Integer>> ans = new ArrayList<>();combine(n, k, 1, new ArrayList<>(), ans);return ans;}private void combine(int n, int k, int cur, List<Integer> list, List<List<Integer>> ans) {if (list.size() == k) {ans.add(new ArrayList<>(list));return;}// 只有当剩余元素数加上已加入列表元素数大于等于k时,才需要继续递归for (int i = cur; n - i + 1 >= k - list.size(); i++) {list.add(i);combine(n, k, i + 1, list, ans);list.remove(list.size() - 1);}}}
