zoukankan      html  css  js  c++  java
  • LeetCode

    Combinations

    2013.12.22 05:17

    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],
    ]

    Solution:

      Combination and permutation problems are usually solved with DFS recursion.

      When solving C(n, k), we pick one element from the candidate set, and solve C(n - 1, k - 1) with the remaining set.

      Time complexity is, eh ...O(C(n, 0) + C(n, 1) + ... + C(n, k)), because the subset (1, 3, 4) comes only after you've searched (1) and (1, 3). ALL smaller subsets must be traversed to get the desired subsets of size k. Space complexity is O(n).

    Accepted code:

     1 // 1AC, very well
     2 class Solution {
     3 public:
     4     vector<vector<int> > combine(int n, int k) {
     5         // IMPORTANT: Please reset any member data you declared, as
     6         // the same Solution instance will be reused for each test case.
     7         int i;
     8         for(i = 0; i < result.size(); ++i){
     9             result[i].clear();
    10         }
    11         result.clear();
    12         
    13         if(n <= 0 || k <= 0){
    14             return result;
    15         }
    16         
    17         arr = new int[n];
    18         dfs(0, 0, n, k);
    19         delete[] arr;
    20         
    21         return result;
    22     }
    23 private:
    24     vector<vector<int>> result;
    25     int *arr;
    26     
    27     void dfs(int idx, int cnt, int n, int k) {
    28         int i;
    29         
    30         if(cnt == k){
    31             result.push_back(vector<int>());
    32             for(i = 0; i < k; ++i){
    33                 result[result.size() - 1].push_back(arr[i]);
    34             }
    35             return;
    36         }
    37         
    38         // trim redundant path to save some time
    39         if(idx + (k - cnt) > n){
    40             return;
    41         }
    42         
    43         for(i = idx; i < n; ++i){
    44             arr[cnt] = i + 1;
    45             dfs(i + 1, cnt + 1, n, k);
    46         }
    47     }
    48 };
  • 相关阅读:
    3.默认参数的注意事项
    2.关键字global,nonlocal
    1.函数的结构,调用,传参,形参,实参,args,kwargs,名称空间,高阶函数
    19. 实现一个整数加法计算器(多个数相加):
    20.文件操作
    18.使用for循环计算+1-3+5-7+9-11+13...99的结果
    ubuntu docker更新镜像源
    虚拟环境的使用
    前端基础之HTML
    jQuery基本使用
  • 原文地址:https://www.cnblogs.com/zhuli19901106/p/3485751.html
Copyright © 2011-2022 走看看