输入: n = 4, k = 2 输出: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]
解题思路
类似之前做过的全排列,思路是一样的,只是不需要从头遍历,直接往下走,深度遍历即可。
代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
class Solution { public List<List<Integer>> combine(int n, int k) { List<List<Integer>> res = new ArrayList<>(); dfs(res, new ArrayList<Integer>(), n, 1, k); return res; } public void dfs(List<List<Integer>> res, List<Integer> list, int n, int index, int k) { if(list.size() == k) { res.add(new ArrayList<>(list)); return ; } for(int i = index; i <= n - (k-list.size()) + 1; i ++) { list.add(i); dfs(res, list, n, i+1, k); list.remove(list.size()-1); } } }
近期评论