首页 > 解决方案 > 检查具有给定总和的数组中的对

问题描述

我正在用c#解决这个问题,

编写一个程序,在给定的整数数组中找到一个给定总和 S(如果存在)的序列。

这是它应该如何工作的

输入:{4, 3, 1, 4, 2, 5, 4}, S = 11 输出:“第一个序列:{4, 2, 5}, 4 + 2 + 5 = 11”,“第二个序列:{2 , 5, 4}, 2 + 5 + 4 = 11"

但是我得到的输出是正确的总和,我也尝试了其他数字

直接从控制台输出:11 11

我的代码:

using System.Collections.Generic;
using System.Linq;

class EntryPoint
{
    static void Main(string[] args)
    {
        int[] arr = { 4, 3, 1, 4, 2, 5, 4 };
        int S = 11;
        int p = 0;
        int[] sumSeq = { };


        for (int i = 0; i < arr.Length; i++)
        {
            p = 0;
            for (int j = 0; j < arr.Length; j++)
            {  
                if (arr[j]!=arr[i])
                {
                    p += arr[j] + arr[i];
                    if (p == S)
                    {

                        Console.WriteLine(p);
                        break;
                        
                        
                    }
                }
                
            }
            
        }
       
       
        
    }
}

标签: c#

解决方案


推荐阅读