题目:https://oj.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], ]
源码:Java版本
算法分析:深搜,递归。时间复杂度O(n!),空间复杂度O(n)
public class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> results=new ArrayList<List<Integer>>();
Stack<Integer> stack=new Stack<Integer>();
combine(n,0,k,stack,results);
return results;
}
private void combine(int n,int start,int k,Stack<Integer> stack,
List<List<Integer>> results) {
if(k==0) {
results.add((Stack<Integer>)(stack.clone()));
return;
}
for(int i=start;i<n;i++) {
stack.push(i+1);
combine(n,i+1,k-1,stack,results);
stack.pop();
}
}
}
本文针对LeetCode上的一道经典组合问题进行详细解析,通过深度优先搜索(DFS)的递归算法实现,提供了完整的Java代码示例。文章深入探讨了算法的时间复杂度为O(n!)与空间复杂度为O(n)的原因。

313

被折叠的 条评论
为什么被折叠?



