zoukankan      html  css  js  c++  java
  • 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],
    ]
    

     分析: 组合的实现,之前实现过全排列,递归求解

    class Solution {
    public:
        vector<vector<int>> combine(int n, int k) {
            //爆搜
            vector<vector<int>> res;
            if (k==0 || n==0)
                return res;
           
            for(int base=1; base<=(n-k+1); base++){
                vector<int> tempres(1,base);
                helper(base,n,k-1,tempres,res);
            }
            return res;
        }
        void helper(int base,int n, int num, vector<int>& tempres, vector<vector<int>>& res){
            if(num==0){
                res.push_back(tempres);
                return;
            }
            if(base+num-1>n){
                return;
            }
            for(int i=base+1; i<=n; i++){
                tempres.push_back(i);
                helper(i,n,num-1,tempres,res);
                tempres.pop_back();
            }
        }
    };
  • 相关阅读:
    好元素(good)
    三条线 (Standard IO)
    计数排序-自然顺序Comparable
    贪心算法之田忌赛马
    bzoj3400
    bzoj1704
    CF Round #456 (Div. 2)
    LA3029
    bzoj3000
    bzoj3623
  • 原文地址:https://www.cnblogs.com/willwu/p/6250585.html
Copyright © 2011-2022 走看看