• 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 };
  • 相关阅读:
    UU跑腿
    Java基础之接口与抽象类的区别
    经典面试题:Redis为什么这么快?
    isBlank与isEmpty
    阅读联机API文档
    从文本中取出链接地址 并检测链接地址能否打开
    2019-01-19=树莓派学习总结
    单片机知识点
    Linux 编程题
    嵌入式基础知识
  • 原文地址:https://www.cnblogs.com/zhuli19901106/p/3485751.html
Copyright © 2020-2023  润新知