77. Combinations
思路很简单,DFS。
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if(k == 0 || n < k) return res;
helper(res,k, new ArrayList<Integer>(),n,1);
return res;
}
public void helper(List<List<Integer>> res, int k, List<Integer> tempList, int n,int m)
{
if(k == 0) res.add(new ArrayList<Integer>(tempList));
for(int i = m; i <= n;i++)
{
//it wont be a valid combination anyway, just break
if(tempList.size() + n + 1 - i < k) break;
tempList.add(i);
helper(res,k-1,tempList,n,i+1);
tempList.remove(tempList.size()-1);
}
}
有几个点需要注意。
一开始傻傻地建立了LIST表示剩下可用的数字,其实不用,一个int K表示当前值,可用的就是k - n
if(tempList.size() + n + 1 - i < k) break;
然后可以提前停止,tempList里现有数量+剩下可用数量 < K
假设需要20个数,现在有10个,然后可用的不足10个,那么怎么组合都没意义,直接BREAK就行
再就是,进入下一层的时候 tempList 比 new ArrayList
三刷。
和前面几个DFS区别不大。。
难点还是在于时间复杂度。。
time: O(n!/k!) = O(n!)
space: O(n)
public class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if (k == 0) return res;
dfs(res, n, k, 1, new ArrayList<>());
return res;
}
public void dfs(List<List<Integer>> res, int n, int k, int m, List<Integer> tempList) {
if (tempList.size() == k) {
res.add(new ArrayList<>(tempList));
} else {
for (int i = m; i <= n; i++) {
tempList.add(i);
dfs(res, n, k, i+1, new ArrayList<>(tempList));
tempList.remove(tempList.size()-1);
}
}
}
}

浙公网安备 33010602011771号