给定两个整数 n 和 k,返回 1 … n 中所有可能的 k 个数的组合。
示例:
输入: n = 4, k = 2 输出: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/combinations 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
写了这么久的回溯 还是不会写 继续抄 不行不行
class Solution { public List<List<Integer>> combine(int n, int k) { List<List<Integer>> res = new ArrayList<>(); if (k <= 0 || n < k) { return res; } // 从 1 开始是题目的设定 Deque<Integer> path = new ArrayDeque<>(); dfs(n, k, 1, path, res); return res; } private void dfs(int n, int k, int began, Deque<Integer> path, List<List<Integer>> list){ if(path.size() == k){ list.add(new ArrayList<>(path)); return; } for( int i = began; i <= n; i ++){ path.add(i); dfs(n, k, i + 1, path, list); path.removeLast(); } } }