首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

一个正整数可以示意为多个正整数相加的格式,写一个函数求有多少种分拆

2013-11-09 
一个正整数可以表示为多个正整数相加的格式,写一个函数求有多少种分拆?一个正整数可以表示为多个正整数相

一个正整数可以表示为多个正整数相加的格式,写一个函数求有多少种分拆?
一个正整数可以表示为多个正整数相加的格式 如 5=1+1+1+1+1,=1+1+1+2,=1+2+2 ,  =1+1+3    =2+3    =1+4,写一个函数求有多少种分拆?

求解!!
[解决办法]
不考虑顺序:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            foreach (var item in foo(5))
                Console.WriteLine(string.Join(" + ", item));
        }

        static IEnumerable<IEnumerable<int>> foo(int n)
        {
            if (n == 1) return new int[][] { new int[] { 1 } };
            return Enumerable.Range(1, n - 1).SelectMany(x => foo(n - x).Where(y => y.Max() <= x).Select(y => y.Concat(new int[] { x })));
        }
    }
}


1 + 1 + 1 + 1 + 1
1 + 1 + 1 + 2
1 + 2 + 2
1 + 1 + 3
1 + 4
Press any key to continue . . .




这是9的:
1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1
1 + 1 + 1 + 1 + 1 + 1 + 1 + 2
1 + 1 + 1 + 1 + 1 + 2 + 2
1 + 1 + 1 + 2 + 2 + 2
1 + 2 + 2 + 2 + 2
1 + 1 + 1 + 1 + 1 + 1 + 3
1 + 1 + 1 + 1 + 2 + 3
1 + 1 + 2 + 2 + 3
1 + 1 + 1 + 3 + 3
1 + 2 + 3 + 3
1 + 1 + 1 + 1 + 1 + 4
1 + 1 + 1 + 2 + 4
1 + 2 + 2 + 4
1 + 1 + 3 + 4
1 + 4 + 4
1 + 1 + 1 + 1 + 5
1 + 1 + 2 + 5
1 + 3 + 5
1 + 1 + 1 + 6
1 + 2 + 6
1 + 1 + 7
1 + 8
Press any key to continue . . .

热点排行