LeetCode-Combinations

题目: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)