【DFS】Combinations
2014-03-18 21:48
337 查看
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:
解法一:递归DFS,在Subsets I的基础上限制个数
public class Solution {
public ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
public void dfs(ArrayList<Integer> l, int n, int k, int pos){
if(l.size() > k) return;
if(l.size() == k){
res.add(new ArrayList(l));
return ;
}
for(int i=pos; i<=n; i++){
l.add(i);
dfs(l, n, k, i+1);
l.remove(l.size() - 1);
}
}
public ArrayList<ArrayList<Integer>> combine(int n, int k) {
ArrayList l = new ArrayList<Integer>();
dfs(l, n, k, 1);
return res;
}
}
For example,
If n = 4 and k = 2, a solution is:
[ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]
解法一:递归DFS,在Subsets I的基础上限制个数
public class Solution {
public ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
public void dfs(ArrayList<Integer> l, int n, int k, int pos){
if(l.size() > k) return;
if(l.size() == k){
res.add(new ArrayList(l));
return ;
}
for(int i=pos; i<=n; i++){
l.add(i);
dfs(l, n, k, i+1);
l.remove(l.size() - 1);
}
}
public ArrayList<ArrayList<Integer>> combine(int n, int k) {
ArrayList l = new ArrayList<Integer>();
dfs(l, n, k, 1);
return res;
}
}
相关文章推荐
- leetcode---letter-combinations-of-a-phone-number---dfs
- Posts Tagged 【dfs】 Combinations
- LeetCode-17 Letter Combinations of a Phone Number(手机拨码-DFS)
- DFS深度遍历 leetcode 17 Letter Combinations of a Phone Number
- Leetcode dfs Letter Combinations of a Phone Number
- LeetCode Letter Combinations of a Phone Number DFS
- LeetCode 17 Letter Combinations of a Phone Number 递归与DFS的使用
- LeetCode Letter Combinations of a Phone Number (DFS)
- Letter Combinations of a Phone Number(带for循环的DFS,组合问题,递归总结)
- LeetCode 17 Letter Combinations of a Phone Number 递归与DFS的使用
- Letter Combinations of a Phone Number(回溯,dfs)
- 【DFS】Letter Combinations of a Phone Number
- DFS Letter Combinations of a Phone Number
- [LeetCode] Combinations (bfs bad、dfs 递归 accept)
- LeetCode-Letter Combinations of a Phone Number-电话号码字母组合-DFS
- leetcode+combinations DFS经典回溯
- leetcode---combinations---dfs
- Combinations(带for循环的DFS)
- DFS Combinations
- Leetcode Letter Combinations of a Phone Number DFS