原文:
给定一组不同的整数和一个和值。打印总和小于给定总和值的所有三元组。预期时间复杂度为 0(n2)。
示例 :
input : arr[] = {-2, 0, 1, 3}
sum = 2.
output : (-2, 0, 1)
(-2, 0, 3)
explanation : the two triplets have sum less than 2.
input : arr[] = {5, 1, 3, 4, 7}
sum = 12.
output : (1, 3, 4)
(1, 3, 5)
(1, 3, 7)
(1, 4, 5)
一个简单的pg电子试玩链接的解决方案是运行三个循环来逐个考虑所有的三胞胎。对于每个三元组,比较总和,如果其总和小于给定总和,则打印当前三元组。
c
// a simple c program to count triplets with sum
// smaller than a given value
#include
using namespace std;
int printtriplets(int arr[], int n, int sum)
{
// fix the first element as a[i]
for (int i = 0; i < n-2; i )
{
// fix the second element as a[j]
for (int j = i 1; j < n-1; j )
{
// now look for the third number
for (int k = j 1; k < n; k )
if (arr[i] arr[j] arr[k] < sum)
cout << arr[i] << ", " << arr[j]
<< ", " << arr[k] << endl;
}
}
}
// driver program
int main()
{
int arr[] = {5, 1, 3, 4, 7};
int n = sizeof arr / sizeof arr[0];
int sum = 12;
printtriplets(arr, n, sum);
return 0;
}
java
// a simple java program to
// count triplets with sum
// smaller than a given value
import java.io.*;
class gfg
{
static int printtriplets(int arr[],
int n, int sum)
{
// fix the first
// element as a[i]
for (int i = 0; i < n - 2; i )
{
// fix the second
// element as a[j]
for (int j = i 1;
j < n - 1; j )
{
// now look for
// the third number
for (int k = j 1; k < n; k )
if (arr[i] arr[j] arr[k] < sum)
system.out.println(arr[i] ", "
arr[j] ", "
arr[k]);
}
}
return 0;
}
// driver code
public static void main (string[] args)
{
int arr[] = {5, 1, 3, 4, 7};
int n = arr.length;
int sum = 12;
printtriplets(arr, n, sum);
}
}
// this code is contributed
// by anuj_67.
python 3
# a simple python 3 program to count
# triplets with sum smaller than a
# given value
def printtriplets(arr, n, sum):
# fix the first element as a[i]
for i in range(0, n - 2, 1):
# fix the second element as a[j]
for j in range(i 1, n - 1, 1):
# now look for the third number
for k in range(j 1, n, 1):
if (arr[i] arr[j] arr[k] < sum):
print(arr[i], ",", arr[j], ",", arr[k])
# driver code
if __name__ == '__main__':
arr =[5, 1, 3, 4, 7]
n = len(arr)
sum = 12
printtriplets(arr, n, sum)
# this code is contributed by
# sahil_shelangia
c
// a simple c# program to
// count triplets with sum
// smaller than a given value
using system;
class gfg
{
static int printtriplets(int[] arr,
int n, int sum)
{
// fix the first
// element as a[i]
for (int i = 0; i < n - 2; i )
{
// fix the second
// element as a[j]
for (int j = i 1;
j < n - 1; j )
{
// now look for
// the third number
for (int k = j 1; k < n; k )
if (arr[i] arr[j] arr[k] < sum)
console.writeline(arr[i] ", "
arr[j] ", "
arr[k]);
}
}
return 0;
}
// driver code
public static void main ()
{
int[] arr = {5, 1, 3, 4, 7};
int n = arr.length;
int sum = 12;
printtriplets(arr, n, sum);
}
}
// this code is contributed
// by mukul singh.
php
javascript
输出:
5, 1, 3
5, 1, 4
1, 3, 4
1, 3, 7
麻将胡了pg电子网站的版权属于:月萌api www.moonapi.com,转载请注明出处