|
顾名思义,贪心法,贪心算法总是做出在当前看来是最好的选择。虽然贪心算法不是对所有问题都能得到整体最优解,但对范围相当广的许多问题都能产生整体最优解或是问题的次优解。因此有很好使用它的必要性。贪心算法既是一种解题策略,也是一种解题思路。
贪心算法,分别用C语言,C++,java,python编写出来
下面是贪心算法(Greedy Algorithm)的不同语言实现示例:
1. C语言:
- #include <stdio.h>
- void greedyAlgorithm(int arr[], int n) {
- int result = 0;
- int i = 0;
- while (i < n) {
- result++;
- int current = arr[i];
- i += current;
- }
- printf("Minimum steps required: %d\n", result);
- }
复制代码 int main() {
int arr[] = {2, 3, 1, 1, 4};
int n = sizeof(arr) / sizeof(arr[0]);
greedyAlgorithm(arr, n);
return 0;
}
2. C++:
- #include <iostream>
- using namespace std;
- void greedyAlgorithm(int arr[], int n) {
- int result = 0;
- int i = 0;
- while (i < n) {
- result++;
- int current = arr[i];
- i += current;
- }
- cout << "Minimum steps required: " << result << endl;
- }
复制代码 int main() {
int arr[] = {2, 3, 1, 1, 4};
int n = sizeof(arr) / sizeof(arr[0]);
greedyAlgorithm(arr, n);
return 0;
}
3. Java:
- public class GreedyAlgorithm {
- public static void greedyAlgorithm(int[] arr) {
- int result = 0;
- int i = 0;
- while (i < arr.length) {
- result++;
- int current = arr[i];
- i += current;
- }
- System.out.println("Minimum steps required: " + result);
- }
-
- }
复制代码 public static void main(String[] args) {
int[] arr = {2, 3, 1, 1, 4};
greedyAlgorithm(arr);
}
4. Python:
- def greedyAlgorithm(arr):
- result = 0
- i = 0
- while i < len(arr):
- result += 1
- current = arr[i]
- i += current
- print("Minimum steps required:", result)
复制代码 arr = [2, 3, 1, 1, 4]
greedyAlgorithm(arr)
|
|