77. Combinations

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.less

Example:code

Input: n = 4, k = 2
Output:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

難度:medium遞歸

題目:給定整數n 和k, 返回1到n 中k個數的全部組合。io

思路:遞歸+剪枝ast

Runtime: 4 ms, faster than 93.58% of Java online submissions for Combinations.
Memory Usage: 43.1 MB, less than 1.39% of Java online submissions for Combinations.class

class Solution {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> result = new ArrayList<>();
        combine(n, 1, k, new Stack<>(), result);
        
        return result;
    }
    
    private void combine(int n, int begin, int k, Stack<Integer> stack, List<List<Integer>> result) {
        if (k <= 0) {
            result.add(new ArrayList<>(stack));
            return;
        }
        
        for (int i = begin; i <= n - k + 1; i++) {
            stack.push(i);
            combine(n, i + 1, k - 1, stack, result);
            stack.pop();
        }
    }
}
相關文章
相關標籤/搜索