📌  相关文章
📜  打印总和为N的前N个自然数的所有可能的K长度子序列

📅  最后修改于: 2021-05-24 19:18:16             🧑  作者: Mango

给定两个正整数NK ,任务是从元素的总和等于N的N个自然数打印所有可能的K长度子序列。

例子:

方法:可以使用回溯技术解决该问题。以下是递归关系:

请按照以下步骤解决问题:

  • 初始化一个二维数组,例如res [] [],以存储所有长度等于和N的长度为K的子序列。
  • 使用上述递归关系,找到所有长度等于和N的长度为K的可能子序列。
  • 最后,打印res [] []数组。

下面是上述方法的实现:

C++
// C++ program to implement
// the above approach
 
#include 
using namespace std;
 
// Function to print all subsequences of length
// K from N natural numbers whose sum equal to N
void findSub(vector >& res, int sum,
             int K, int N, vector& temp)
{
 
    // Base case
    if (K == 0 && sum == 0) {
        res.push_back(temp);
        return;
    }
    if (sum <= 0 || K <= 0) {
        return;
    }
 
    // Iterate over the range [1, N]
    for (int i = 1; i <= N; i++) {
 
        // Insert i into temp
        temp.push_back(i);
        findSub(res, sum - i, K - 1, N, temp);
 
        // Pop i from temp
        temp.pop_back();
    }
}
 
// Utility function to print all subsequences
// of length K with sum equal to N
void UtilPrintSubsequncesOfKSumN(int N, int K)
{
 
    // Store all subsequences of length K
    // from N natural numbers
    vector > res;
 
    // Store current subsequence of
    // length K from N natural numbers
    vector temp;
 
    findSub(res, N, K, N, temp);
 
    // Stores total count
    // of subsequences
    int sz = res.size();
 
    // Print all subsequences
    cout << "{ ";
 
    // Treaverse all subsequences
    for (int i = 0; i < sz; i++) {
 
        cout << "{ ";
 
        // Print current subsequence
        for (int j = 0; j < K; j++) {
 
            // If current element is last
            // element of subsequence
            if (j == K - 1)
                cout << res[i][j] << " ";
            else
                cout << res[i][j] << ", ";
        }
 
        // If current subsequence is last
        // subsequence from n natural numbers
        if (i == sz - 1)
            cout << "}";
        else
            cout << "}, ";
    }
    cout << " }";
}
 
// Driver Code
int main()
{
 
    int N = 4;
    int K = 2;
    UtilPrintSubsequncesOfKSumN(N, K);
}


Java
// Java program to implement
// the above approach
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
 
class GFG {
 
  // Function to print all subsequences of length
  // K from N natural numbers whose sum equal to N
  static void findSub(List > res, int sum,
                      int K, int N, List temp)
  {
 
    // Base case
    if (K == 0 && sum == 0) {
      List newList = temp.stream().collect(
        Collectors.toList());
      res.add(newList);
      return;
    }
    if (sum <= 0 || K <= 0) {
      return;
    }
 
    // Iterate over the range [1, N]
    for (int i = 1; i <= N; i++) {
 
      // Insert i into temp
      temp.add(i);
      findSub(res, sum - i, K - 1, N, temp);
 
      // Pop i from temp
      temp.remove(temp.size() - 1);
    }
  }
 
  // Utility function to print all subsequences
  // of length K with sum equal to N
  static void UtilPrintSubsequncesOfKSumN(int N, int K)
  {
 
    // Store all subsequences of length K
    // from N natural numbers
    @SuppressWarnings("unchecked")
    List > res = new ArrayList();
 
    // Store current subsequence of
    // length K from N natural numbers
    @SuppressWarnings("unchecked")
    List temp = new ArrayList();
 
    findSub(res, N, K, N, temp);
 
    // Stores total count
    // of subsequences
    int sz = res.size();
 
    // Print all subsequences
    System.out.print("{ ");
 
    // Treaverse all subsequences
    for (int i = 0; i < sz; i++) {
 
      System.out.print("{ ");
 
      // Print current subsequence
      for (int j = 0; j < K; j++) {
 
        // If current element is last
        // element of subsequence
        if (j == K - 1)
          System.out.print(res.get(i).get(j)
                           + " ");
        else
          System.out.print(res.get(i).get(j)
                           + ", ");
      }
 
      // If current subsequence is last
      // subsequence from n natural numbers
      if (i == sz - 1)
        System.out.print("}");
      else
        System.out.print("}, ");
    }
    System.out.print(" }");
  }
 
  // Driver code
  public static void main(String[] args)
  {
    int N = 4;
    int K = 2;
    UtilPrintSubsequncesOfKSumN(N, K);
  }
}
 
// This code is contributed by jithin.


输出:
{ { 1, 3 }, { 2, 2 }, { 3, 1 } }

时间复杂度: O(2 N )
辅助空间: O(X),其中X表示总和为N的长度为K的子序列的计数