📜  零钱| BFS方法

📅  最后修改于: 2021-04-24 05:02:46             🧑  作者: Mango

给定一个整数X和一个长度N的数组arr [] ,该数组由正整数组成,任务是从数组中选择最小数量的整数,使它们的总和为N。可以选择任意数量的次数。如果不存在答案,则打印-1
例子:

方法:本文已经介绍了如何使用动态编程方法解决此问题。
在这里,我们将看到使用BFS解决此问题的方法略有不同。
在此之前,让我们继续定义状态。可以将状态S X定义为我们需要从数组中获取X的总数的最小整数。
现在,如果我们开始将每个状态视为图中的一个节点,以使每个节点都连接到(S X – arr [0] ,S X – arr [1] ,…S X – arr [N – 1] )
因此,我们必须在未加权的情况下找到从状态N0的最短路径,这可以使用BFS来完成。 BFS在这里起作用,因为该图未加权。
下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Function to find the minimum number
// of integers required
int minNumbers(int x, int* arr, int n)
{
    // Queue for BFS
    queue q;
 
    // Base value in queue
    q.push(x);
 
    // Boolean array to check if a number has been
    // visited before
    unordered_set v;
 
    // Variable to store depth of BFS
    int d = 0;
 
    // BFS algorithm
    while (q.size()) {
 
        // Size of queue
        int s = q.size();
        while (s--) {
 
            // Front most element of the queue
            int c = q.front();
 
            // Base case
            if (!c)
                return d;
            q.pop();
            if (v.find(c) != v.end() or c < 0)
                continue;
 
            // Setting current state as visited
            v.insert(c);
 
            // Pushing the required states in queue
            for (int i = 0; i < n; i++)
                q.push(c - arr[i]);
        }
 
        d++;
    }
 
    // If no possible solution
    return -1;
}
 
// Driver code
int main()
{
    int arr[] = { 3, 3, 4 };
    int n = sizeof(arr) / sizeof(int);
    int x = 7;
 
    cout << minNumbers(x, arr, n);
 
    return 0;
}


Java
// Java implementation of the approach
import java.util.*;
 
class GFG
{
 
// Function to find the minimum number
// of integers required
static int minNumbers(int x, int []arr, int n)
{
    // Queue for BFS
    Queue q = new LinkedList<>();
 
    // Base value in queue
    q.add(x);
 
    // Boolean array to check if
    // a number has been visited before
    HashSet v = new HashSet();
 
    // Variable to store depth of BFS
    int d = 0;
 
    // BFS algorithm
    while (q.size() > 0)
    {
 
        // Size of queue
        int s = q.size();
        while (s-- > 0)
        {
 
            // Front most element of the queue
            int c = q.peek();
 
            // Base case
            if (c == 0)
                return d;
            q.remove();
            if (v.contains(c) || c < 0)
                continue;
 
            // Setting current state as visited
            v.add(c);
 
            // Pushing the required states in queue
            for (int i = 0; i < n; i++)
                q.add(c - arr[i]);
        }
        d++;
    }
 
    // If no possible solution
    return -1;
}
 
// Driver code
public static void main(String[] args)
{
    int arr[] = { 3, 3, 4 };
    int n = arr.length;
    int x = 7;
 
    System.out.println(minNumbers(x, arr, n));
}
}
 
// This code is contributed by Rajput-Ji


Python3
# Python3 implementation of the approach
 
# Function to find the minimum number
# of integers required
def minNumbers(x, arr, n) :
 
    q = []
 
    # Base value in queue
    q.append(x)
 
    v = set([])
 
    d = 0
 
    while (len(q) > 0) :
 
        s = len(q)
        while (s) :
            s -= 1
            c = q[0]
            #print(q)
            if (c == 0) :
                return d
            q.pop(0)
            if ((c in v) or c < 0) :
                continue
 
            # Setting current state as visited
            v.add(c)
 
            # Pushing the required states in queue
            for i in range(n) :
                q.append(c - arr[i])            
             
        d += 1
        #print()
        #print(d,c)
 
    # If no possible solution
    return -1
 
arr = [ 1, 4,6 ]
n = len(arr)
x = 20
print(minNumbers(x, arr, n))
 
# This code is contributed by divyeshrabadiya07
# Improved by nishant.k108


C#
// C# implementation of the approach
using System;
using System.Collections.Generic;
     
class GFG
{
 
// Function to find the minimum number
// of integers required
static int minNumbers(int x, int []arr, int n)
{
    // Queue for BFS
    Queue q = new Queue();
 
    // Base value in queue
    q.Enqueue(x);
 
    // Boolean array to check if
    // a number has been visited before
    HashSet v = new HashSet();
 
    // Variable to store depth of BFS
    int d = 0;
 
    // BFS algorithm
    while (q.Count > 0)
    {
 
        // Size of queue
        int s = q.Count;
        while (s-- > 0)
        {
 
            // Front most element of the queue
            int c = q.Peek();
 
            // Base case
            if (c == 0)
                return d;
            q.Dequeue();
            if (v.Contains(c) || c < 0)
                continue;
 
            // Setting current state as visited
            v.Add(c);
 
            // Pushing the required states in queue
            for (int i = 0; i < n; i++)
                q.Enqueue(c - arr[i]);
        }
        d++;
    }
 
    // If no possible solution
    return -1;
}
 
// Driver code
public static void Main(String[] args)
{
    int []arr = { 3, 3, 4 };
    int n = arr.Length;
    int x = 7;
 
    Console.WriteLine(minNumbers(x, arr, n));
}
}
 
// This code is contributed by Rajput-Ji


输出:
2

时间复杂度: O(N * X)