📜  使用回溯,具有给定总和的最大大小子集

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

给定一个由N个整数和一个整数K组成的数组arr [] ,任务是找到总和等于K的最长子序列的长度。
例子:

天真的方法:解决问题的最简单方法是生成所有可能的不同长度的子序列,并检查它们的总和是否等于K。在所有这些具有和K的子序列中,找到长度最长的子序列。
时间复杂度: O(2 N )
递归和回溯方法:此问题的基本方法是对向量进行排序,找到所有可能的子序列的和,然后拾取具有给定总和的最大长度的子序列。这可以使用递归和回溯来完成。
请按照以下步骤解决此问题:

  • 对给定的数组/向量进行排序。
  • 将全局变量max_length初始化为0,该变量存储最大长度子集。
  • 对于数组中的每个索引i ,调用递归函数以找出所有可能的子集,这些子集具有[i,N-1]范围内的元素之和为K。
  • 每次找到总和为K的子集时,请检查其大小是否大于当前的max_length值。如果是,则更新max_length的值。
  • 计算完所有可能的子集和之后,返回max_length

下面是上述方法的实现:

C++
// C++ Program to implement the
// above approach
#include 
using namespace std;
 
// Initialise maximum possible
// length of subsequence
int max_length = 0;
 
// Store elements to compare
// max_length with its size
// and change the value of
// max_length accordingly
vector store;
 
// Store the elements of the
// longest subsequence
vector ans;
 
// Function to find the length
// of longest subsequence
void find_max_length(
    vector& arr,
    int index, int sum, int k)
{
    sum = sum + arr[index];
    store.push_back(arr[index]);
    if (sum == k) {
        if (max_length < store.size()) {
            // Update max_length
            max_length = store.size();
 
            // Store the subsequence
            // elements
            ans = store;
        }
    }
 
    for (int i = index + 1;
         i < arr.size(); i++) {
        if (sum + arr[i] <= k) {
 
            // Recursively proceed
            // with obtained sum
            find_max_length(arr, i,
                            sum, k);
 
            // poping elements
            // from back
            // of vector store
            store.pop_back();
        }
 
        // if sum > 0 then we don't
        // required thatsubsequence
        // so return and continue
        // with earlier elements
        else
            return;
    }
 
    return;
}
 
int longestSubsequence(vector arr,
                       int n, int k)
{
 
    // Sort the given array
    sort(arr.begin(), arr.end());
 
    // Traverse the array
    for (int i = 0; i < n; i++) {
        // If max_length is already
        // greater than or equal
        // than remaining length
        if (max_length >= n - i)
            break;
 
        store.clear();
 
        find_max_length(arr, i, 0, k);
    }
 
    return max_length;
}
 
// Driver code
int main()
{
    vector arr{ -3, 0, 1, 1, 2 };
    int n = arr.size();
    int k = 1;
 
    cout << longestSubsequence(arr,
                               n, k);
 
    return 0;
}


Java
// Java Program to implement the
// above approach
import java.util.*;
class GFG{
  
// Initialise maximum possible
// length of subsequence
static int max_length = 0;
  
// Store elements to compare
// max_length with its size
// and change the value of
// max_length accordingly
static Vector store = new Vector();
  
// Store the elements of the
// longest subsequence
static Vector ans = new Vector();
  
// Function to find the length
// of longest subsequence
static void find_max_length(
    int []arr,
    int index, int sum, int k)
{
    sum = sum + arr[index];
    store.add(arr[index]);
    if (sum == k)
    {
        if (max_length < store.size())
        {
            // Update max_length
            max_length = store.size();
  
            // Store the subsequence
            // elements
            ans = store;
        }
    }
  
    for (int i = index + 1;
             i < arr.length; i++)
    {
        if (sum + arr[i] <= k)
        {
  
            // Recursively proceed
            // with obtained sum
            find_max_length(arr, i,
                            sum, k);
  
            // poping elements
            // from back
            // of vector store
            store.remove(store.size() - 1);
        }
  
        // if sum > 0 then we don't
        // required thatsubsequence
        // so return and continue
        // with earlier elements
        else
            return;
    }
    return;
}
  
static int longestSubsequence(int []arr,
                                 int n, int k)
{
  
    // Sort the given array
    Arrays.sort(arr);
  
    // Traverse the array
    for (int i = 0; i < n; i++)
    {
        // If max_length is already
        // greater than or equal
        // than remaining length
        if (max_length >= n - i)
            break;
  
        store.clear();
  
        find_max_length(arr, i, 0, k);
    }
    return max_length;
}
  
// Driver code
public static void main(String[] args)
{
    int []arr = { -3, 0, 1, 1, 2 };
    int n = arr.length;
    int k = 1;
  
    System.out.print(longestSubsequence(arr,
                                           n, k));
}
}
 
// This code is contributed by Princi Singh


Python3
# Python3 Program to implement the
# above approach
# Initialise maximum possible
# length of subsequence
max_length = 0
 
# Store elements to compare
# max_length with its size
# and change the value of
# max_length accordingly
store = []
 
# Store the elements of the
# longest subsequence
ans = []
 
# Function to find the length
# of longest subsequence
def find_max_length(arr, index, sum, k): 
    global max_length
    sum = sum + arr[index]
    store.append(arr[index])
    if (sum == k):
        if (max_length < len(store)):
            # Update max_length
            max_length = len(store)
 
            # Store the subsequence
            # elements
            ans = store
 
    for i in range ( index + 1, len(arr)):
        if (sum + arr[i] <= k):
 
            # Recursively proceed
            # with obtained sum
            find_max_length(arr, i,
                            sum, k)
 
            # poping elements
            # from back
            # of vector store
            store.pop()
        
        # if sum > 0 then we don't
        # required thatsubsequence
        # so return and continue
        # with earlier elements
        else:
            return
    return
 
def longestSubsequence(arr, n, k):
 
    # Sort the given array
    arr.sort()
 
    # Traverse the array
    for i in range (n):
       
        # If max_length is already
        # greater than or equal
        # than remaining length
        if (max_length >= n - i):
            break
 
        store.clear()
        find_max_length(arr, i, 0, k)
    
    return max_length
 
# Driver code
if __name__ == "__main__":
   
    arr = [-3, 0, 1, 1, 2]
    n = len(arr)
    k = 1
    print (longestSubsequence(arr, n, k))
     
# This code is contributed by Chitranayal


C#
// C# program to implement the
// above approach
using System;
using System.Collections.Generic;
class GFG{
 
// Initialise maximum possible
// length of subsequence
static int max_length = 0;
 
// Store elements to compare
// max_length with its size
// and change the value of
// max_length accordingly
static List store = new List();
 
// Store the elements of the
// longest subsequence
static List ans = new List();
 
// Function to find the length
// of longest subsequence
static void find_max_length(int []arr,
                            int index,
                            int sum, int k)
{
    sum = sum + arr[index];
    store.Add(arr[index]);
     
    if (sum == k)
    {
        if (max_length < store.Count)
        {
             
            // Update max_length
            max_length = store.Count;
 
            // Store the subsequence
            // elements
            ans = store;
        }
    }
 
    for(int i = index + 1;
            i < arr.Length; i++)
    {
        if (sum + arr[i] <= k)
        {
 
            // Recursively proceed
            // with obtained sum
            find_max_length(arr, i,
                            sum, k);
 
            // poping elements
            // from back
            // of vector store
            store.RemoveAt(store.Count - 1);
        }
 
        // If sum > 0 then we don't
        // required thatsubsequence
        // so return and continue
        // with earlier elements
        else
            return;
    }
    return;
}
 
static int longestSubsequence(int []arr,
                              int n, int k)
{
 
    // Sort the given array
    Array.Sort(arr);
 
    // Traverse the array
    for(int i = 0; i < n; i++)
    {
         
        // If max_length is already
        // greater than or equal
        // than remaining length
        if (max_length >= n - i)
            break;
 
        store.Clear();
 
        find_max_length(arr, i, 0, k);
    }
    return max_length;
}
 
// Driver code
public static void Main(String[] args)
{
    int []arr = { -3, 0, 1, 1, 2 };
    int n = arr.Length;
    int k = 1;
 
    Console.Write(longestSubsequence(arr,
                                     n, k));
}
}
 
// This code is contributed by gauravrajput1


输出:
5


时间复杂度: O(N 3 )
辅助空间: O(N)
动态编程方法:有关解决此问题的进一步优化方法,请参阅本文。