zoukankan      html  css  js  c++  java
  • Java实现 LeetCode 77 组合

    77. 组合

    给定两个整数 n 和 k,返回 1 … n 中所有可能的 k 个数的组合。

    示例:

    输入: n = 4, k = 2
    输出:
    [
    [2,4],
    [3,4],
    [2,3],
    [1,2],
    [1,3],
    [1,4],
    ]

    class Solution {
         private List<List<Integer>> res;
        
        public List<List<Integer>> combine(int n, int k) {
            
            res = new ArrayList<List<Integer>>();
            if (n<1 || k<1 || n<k) {
                return res;
            }
            List<Integer> selected = new ArrayList<Integer>();
            pickNext(1, n, k, selected);
            return res;
        }
        
        public void pickNext(int min, int max, int k, List<Integer> selected) {
            
            if (k==0) {
                res.add(new ArrayList<Integer>(selected));
                return;
            }
            
            for (int i=min; i<=max-k+1; i++) {
                selected.add(i);
                pickNext(i+1, max, k-1, selected);
                selected.remove(selected.size()-1);
            }
        }
    }
    
  • 相关阅读:
    解释器模式
    命令模式
    责任链模式
    代理模式
    享元模式
    外观模式
    装饰器模式
    组合模式
    过滤器模式
    js广告浮动
  • 原文地址:https://www.cnblogs.com/a1439775520/p/13076243.html
Copyright © 2011-2022 走看看