【Leetcode】77. Combinations
来源:互联网 发布:77pepecom现在域名 编辑:程序博客网 时间:2024/06/08 21:08
先贴代码:
转载自:http://blog.csdn.net/happyaaaaaaaaaaa/article/details/51564160
public class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> resList = new ArrayList<List<Integer>>();
List<Integer> temp = new ArrayList<Integer>();
dfs(resList,temp,n,k,1);
return resList;
}
private void dfs(List<List<Integer>> res,List<Integer> temp,int n,int k,int m){
if(k == 0){
res.add(new ArrayList<Integer>(temp));
}
for(int i=m;i<=n;i++){
temp.add(i);
dfs(res,temp,n,k-1,i+1);
temp.remove(temp.size()-1);//吐出当前这个
}
}
}
该解法只用了一个额外的空间,通过不断的递归来解决这个问题。
每次如果选中一个节点,进入递归,当元素选满的时候退出。
每次递归结束的时候弹出最后一个节点,随后进入下次递归,从而遍历了所有的可能结果。
贴上运行结果:(还行)
PS:对于深度优先和广度优先树的题目总感觉无从下手~~~留坑,等我找到提升速度的方式
- LeetCode 77. Combinations
- [LeetCode]77.Combinations
- LeetCode --- 77. Combinations
- [Leetcode] 77. Combinations
- [leetcode] 77.Combinations
- leetCode 77.Combinations (组合)
- [leetcode] 77. Combinations
- 77. Combinations LeetCode
- <LeetCode OJ> 77. Combinations
- [LeetCode]77. Combinations
- leetcode 77. Combinations
- LeetCode *** 77. Combinations
- leetcode 77. Combinations
- LeetCode 77. Combinations
- LeetCode-77.Combinations
- LeetCode 77.Combinations
- [LeetCode]problem 77. Combinations
- [LeetCode] 77. Combinations
- 安卓底层开发学习经验第二十期
- HDOJ--1248|寒冰王座
- 程序运行的时间的估算
- [hihocoder1032]最长回文子串
- DPDK中文-DPDK的ring
- 【Leetcode】77. Combinations
- 合并两个单向链表
- PL/SQL错误提示 database character set(AL32UTF8) and Client character set(ZHS16GBK) are different
- substance在java swing中使用注意事项
- Android 提示框Toast不显示的问题
- 欢迎使用CSDN-markdown编辑器
- 代码优化
- Java 学习笔记 Day003
- 视频前背景分离论文之(2) GOSUS: Grassmannian Online Subspace Updates with Structured-sparsity