递归 找出自然数1,2,3....n 中任取r个数的所有组合。

来源:互联网 发布:nba2k18科比捏脸数据 编辑:程序博客网 时间:2024/05/16 14:12

递归 找出自然数1,2,3....n 中任取r个数的所有组合。例如 n = 5 ,r=3 所有组合
5 4 3
5 4 2
5 4 1
5 3 2
5 3 1
5 2 1
4 3 2
4 3 1
4 2 1
3 2 1

using System;
using System.Collections.Generic;
using System.Text;

namespace MyTest
{
    class Program
    {
        static int[] a = new int[100];
        static void Main(string[] args)
        {
            int n, r;
            Console.Write("请输入n:");
            n = Convert.ToInt32(Console.ReadLine());
            Console.Write("请输入r:");
            r = Convert.ToInt32(Console.ReadLine());
            if (n < r)
            {
                Console.WriteLine("n不能小于r");
                Console.ReadLine();
            }
            a[0] = r;
            comb(n, r);
            Console.ReadLine();
        }
       
        static void comb(int m, int k)
        {
            int i,j;
            for (i = m; i >= k; i--)
            {
                a[k] = i;
                if (k > 1)
                {
                    comb(i - 1, k - 1);
                }
                else
                {
                    for (j = a[0]; j >0; j--)
                    {
                        Console.Write(a[j].ToString() +"  ");
                    }
                    Console.WriteLine();
                }
            }
        }
    }
}