计算一个数等于其它数相加的所有可能 如: 5 =1+4 ,1+3+1,2+3,2+2+1,1+1+1+1+1,1+1+1+2

初一看,这不好实现。如果是1000 还有1000个1相加。所以单纯的写for循环是不行的,当时感觉 第一循环的嵌套层数无法确认,第二 循环的结束条件是什么?

一开始想到了递归。

代码如下:

 

 1  static void Main(string[] args)
 2         {
 3             int K = 5;
 4 
 5              for (int i = 1; i <= K/2; i++)
 6             {
 7                 fun(i.ToString(), i, K-i);
 8             }
 9             Console.ReadLine();
10         }
11 
12    public static void fun(string str, int i, int N)
13         {
14 
15             if (N == 0) return;          
16             Console.WriteLine(str+"+"+N );
17             str += "+1";
18             fun(str, i, N - 1);
19 
20         }

但是这样发现有重复的,比如 1+1+1+2 与 2+1+1+1

看上面的结果,发现就多了最后一条,所以只要最后一个数不要小于第一个数就可以了。

代码如下:

 1 static void Main(string[] args)
 2           {
 3               int K = 5;
 4              for (int i = 1; i <= K / 2; i++)
 5               {
 6                              fun("", i, K - i);
 7  
 8               }
 9   
10                    Console.ReadLine();
11          }
12 
13  public static void fun(string str, int first, int N)
14         {
15 
16             if (N == 0) return;
str+= first+ "+";
17 Console.WriteLine(str + N); 18 19 if (first <= N - 1) //判断后半不能与前面重。 20 fun(str, first, N - 1); 21 22 }

结果如下:

 

发现一个问题:以上代码没有实现全,像6=2+2+2 这种会丢失.

fun方法更正如下:

 1  public static void fun(string str, int first,int N)
 2         {
 3 
 4             if (N == 0) return;
 5             str += first + "+";
 6             Console.WriteLine(str + N);
 7 
 8             for (int i = first; i <= N - 1; i++)
 9             {
10                 if (i <= N - i)
11                     fun(str, i, N - i);
12 
13             }
14 
15 
16         }

 

 

 

posted on 2014-04-26 18:06  MyFlyFish  阅读(432)  评论(0编辑  收藏  举报

导航