zoukankan      html  css  js  c++  java
  • 19.2.15 [LeetCode 77] Combinations

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

    Example:

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

    题意

    在1到n中取k个数的所有情况

    题解

     1 class Solution {
     2 public:
     3     void build(vector<vector<int>>&ans,vector<int>&now, int n, int k) {
     4         if (k == 0) {
     5             ans.push_back(now);
     6             return;
     7         }
     8         int s = 0;
     9         if (!now.empty())s = now.back();
    10         for (int i = s + 1; i <= n - k + 1; i++) {
    11             now.push_back(i);
    12             build(ans, now, n, k - 1);
    13             now.pop_back();
    14         }
    15     }
    16     vector<vector<int>> combine(int n, int k) {
    17         vector<vector<int>>ans;
    18         vector<int>now;
    19         build(ans, now, n, k);
    20         return ans;
    21     }
    22 };
    View Code
  • 相关阅读:
    自介
    打招呼
    试验四
    作业:实验二
    个人简介
    实验4
    构建之法—心得体会
    作业:实验二
    个人简介
    软件测试第四次博客作业2
  • 原文地址:https://www.cnblogs.com/yalphait/p/10384032.html
Copyright © 2011-2022 走看看