【问题标题】:How to fill an array recursively如何递归地填充数组
【发布时间】:2021-12-11 10:12:59
【问题描述】:

您好,我了解如何用循环迭代填充数组。但是为了理解和弥合复杂性的差距,我想知道如何递归地解决这个问题。

问题是让'n'成为数组'nums'的索引。 nums 将所有以前的数字存储在它的数组中。例如,n=6; nums = [0=6],[1=5],[2=4],[3=3],[4=2],[5=1]。

static void Main(string[] args)
{
  int n = 6;
  int[] nums = new int[n];

  for(int i = 0;i < nums.Length; i++)
  {
      Console.WriteLine(fillArray(nums, n)[i]); //expected output 6,5,4,3,2,1
  }
}
static int[] fillArray(int[] nums, n)
{
    for(int i = 0; i< nums.Length; i++)
    {
        nums[i] = n--;
    }
   return nums;
}

非常感谢,谢谢大家的回复!

【问题讨论】:

    标签: c# arrays recursion data-structures


    【解决方案1】:

    你可以试试这个:

        static void fillArray(int[] nums, int index, int n)
        {
            if(index == nums.Length)
            {
                return;
            }else 
            {
                nums[index] = n;
                fillArray(nums, index + 1, n - 1);
            }
        }
    
        static void Main(string[] args)
        {
            int n = 6;
            int[] nums = new int[n];
            fillArray(nums, 0, n);
    
            for(int i = 0;i < nums.Length; i++)
            {
                Console.WriteLine(nums[i]); //expected output 6,5,4,3,2,1
            }
        }
    

    【讨论】:

    • @JohnG 现在测试它并意识到我犯了一个错误。感谢您指出。
    猜你喜欢
    • 2016-07-13
    • 2015-06-29
    • 1970-01-01
    • 2013-12-08
    • 2013-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-17
    相关资源
    最近更新 更多