首页 > 解决方案 > C#如何打印加到给定数字的组合?

问题描述

我正在尝试使用动态编程用 C# 实现“将 N 表示为其他数字的总和的不同方式的计数”问题。我的方法看起来像:

 static int howManyWays(int n) 
    { 
        int [] safe= new int[n + 1]; 

        // base cases 
        safe[0] = safe[1] = safe[2] = 1; 
        safe[3] = 2; 

        // iterate for all values from 4 to n 
        for (int i = 4; i <= n; i++) 
            safe[i] = safe[i - 1] + safe[i - 3]  
                    + safe[i - 4]; 

        return safe[n]; 
    } 

例如,如果我选择nas n = 4,那么我的结果是:

4 

我想打印出这 4 种总和组合:

 1+1+1+1 
 1+3
 3+1 
 4 

有没有办法递归或使用动态编程来做到这一点?我的尝试是递归地获得一组组合:

static int[]  Combs(int n)
        {
            int[] tusc = { };

            if (n < 0)
                yield break;
            if (n == 0)
                yield return tusc;
            int[] X = { 1, 3, 4 };
            for(int i = 0; i < X.Length; i++)
            {
                for(j = 0; j <= Combs(n-X[i]).Length; j++)
                {
                    yield return X + j;
                }

            }

        }

在python中工作的原始代码,但不知道如何翻译成C#:

def combis(n):
    if n < 0:
        return
    if n == 0:
        yield []
    for x in (1, 3, 4):
        for combi in combis(n-x):
            yield [x] + combi

>>> list(combis(5))
[[1, 1, 1, 1, 1], [1, 1, 3], [1, 3, 1], [1, 4], [3, 1, 1], [4, 1]]

标签: c#recursiondynamicnumbersadd

解决方案


这是一个非常直接的翻译:

using System;
using System.Collections.Generic;

class MainClass 
{
    static IEnumerable<List<int>> Combs(int n)
    {
        if (n < 0)
        {
            yield break;
        } 
        else if (n == 0) 
        {
            yield return new List<int>();
        }

        foreach (int x in new List<int>() {1, 3, 4})
        {
            foreach (IEnumerable<int> combi in Combs(n - x))
            {       
                var result = new List<int>() {x};
                result.AddRange(combi);
                yield return result;
            }

        }
    }

    public static void Main(string[] args) 
    {
        foreach (IEnumerable<int> nums in Combs(5))
        {
            foreach (var i in nums) 
            {
                Console.Write(i + ", ");
            }

            Console.WriteLine();
        }
    }
}

输出:

1, 1, 1, 1, 1, 
1, 1, 3, 
1, 3, 1, 
1, 4, 
3, 1, 1, 
4, 1, 

评论:

  • 由于您使用的是yield,因此请将标头更改Combs为返回IEnumerable<int>而不是int[]
  • 使用列表而不是固定长度的数组,并从 PythonList.AddRange转换列表连接操作。+
  • 翻译有些混乱X。在 Python 版本中,x它只是选项列表中的一个元素,{1, 3, 4}但在 C# 版本中,它是整个数组。
  • Combs(n-X[i]).Length没有意义——它调用Combs,获取结果的长度,然后丢弃所有结果,所以它就像一个非常昂贵的计数器。j为您提供一个计数器索引,而不是预期的子Combs调用中的元素之一。foreach是 Pythonfor .. in循环的最准确翻译。
  • {1, 3, 4}列表可能应该被制成一个参数,以允许调用者控制其行为。
  • 效率很差,因为要重新计算重叠的子问题。改进它作为一个练习(这可能是你的下一步)。

推荐阅读