📌  相关文章
📜  查找第 K 个字典顺序最小的子数组

📅  最后修改于: 2022-05-13 01:56:05.233000             🧑  作者: Mango

查找第 K 个字典顺序最小的子数组

给定一个包含N个整数的数组arr[] ,任务是找到给定数组的第 K字典序最小子集。

例子:

方法:给定问题可以通过生成给定数组的所有幂集,然后按字典顺序对幂集的子集进行排序来解决。因此,排序后的幂集的第K索引处的子集是所需的答案。

下面是上述方法的实现:

C++
// C++ Program of the above approach
#include 
using namespace std;
 
// Function to find the power set of the
// given array
vector > powerSet(int* arr, int N)
{
    int pow1 = pow(2, N);
 
    // Stores the power set
    vector > v;
 
    // Loop to iterate over all elements of
    // the power set
    for (int count = 0; count < pow1; count++) {
 
        // Stores the current subset
        vector temp;
        for (int j = 0; j < N; j++) {
            if (count & (1 << j)) {
                temp.push_back(arr[j]);
            }
        }
 
        // Sorting the current subset
        sort(temp.begin(), temp.end());
        if (count != 0) {
            v.push_back(temp);
        }
    }
 
    // Return Power Ser
    return v;
}
 
// Function to find the
// Kth lexicographic smallest
// subset of the given array
vector kthSmallestSubset(
    int* arr, int N, int K)
{
    // Stores the power set
    vector > powSet
        = powerSet(arr, N);
 
    // Sort the power set
    // in lexicographic order
    sort(powSet.begin(), powSet.end());
 
    // Return Answer
    return powSet[K - 1];
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 2, 3, 4 };
    int N = sizeof(arr) / sizeof(arr[0]);
    int K = 5;
 
    vector ans
        = kthSmallestSubset(arr, N, K);
    for (auto x : ans) {
        cout << x << " ";
    }
}


Python3
# Python Program of the above approach
 
# Function to find the power set of the
# given array
def powerSet(arr, N):
  pow1 = 2 ** N
 
  # Stores the power set
  v = [];
 
  # Loop to iterate over all elements of
  # the power set
  for count in range(pow1):
 
    # Stores the current subset
    temp = []
    for j in range(N):
      if (count & (1 << j)):
        temp.append(arr[j]);
 
    # Sorting the current subset
    temp.sort();
    if (count != 0):
      v.append(temp);
 
  # Return Power Ser
  return v;
 
# Function to find the
# Kth lexicographic smallest
# subset of the given array
def kthSmallestSubset(arr, N, K):
   
  # Stores the power set
  powSet = powerSet(arr, N);
 
  # Sort the power set
  # in lexicographic order
  powSet.sort();
 
  # Return Answer
  return powSet[K - 1];
 
# Driver Code
arr = [1, 2, 3, 4];
N = len(arr)
K = 5;
 
ans = kthSmallestSubset(arr, N, K);
for x in ans:
  print(x, end=" ");
 
  # This code is contributed by gfgking.


Javascript


输出
1 2 4 

时间复杂度: O(N * 2 N )
辅助空间: O(2 N )