https://leetcode.com/problems/combinations/
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
For example,
If n = 4 and k = 2, a solution is:
[ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]
解题思路:
最基本的组合题目,DFS+回溯,遇到了去重,解决方法也比较基本。现在写起来轻松多了。
public class Solution { public List<List<Integer>> combine(int n, int k) { List<List<Integer>> result = new LinkedList<List<Integer>>(); List<Integer> current = new LinkedList<Integer>(); int[] dict = new int[n]; for(int i = 0; i < n; i++){ dict[i] = i + 1; } dfs(result, current, dict, k, 0); return result; } public void dfs(List<List<Integer>> result, List<Integer> current, int[] dict, int k, int step){ if(current.size() == k){ result.add(new LinkedList(current)); return; } for(int i = step; i < dict.length; i++){ current.add(dict[i]); dfs(result, current, dict, k, i + 1); current.remove(current.size() - 1); } } }
注意是i+1,不是step+1。
5个参数的解法
public class Solution { public List<List<Integer>> combine(int n, int k) { List<List<Integer>> res = new ArrayList<List<Integer>>(); if(n == 0) { return res; } dfs(n, k, res, new ArrayList<Integer>(), 1); return res; } public void dfs(int n, int k, List<List<Integer>> res, List<Integer> cur, int start) { if(cur.size() == k) { res.add(new ArrayList(cur)); return; } for(int i = start; i <= n; i++) { cur.add(i); dfs(n, k, res, cur, i + 1); cur.remove(cur.size() - 1); } } }