常用算法(C#): 用回溯法找出 n 个自然数中取 r 个数的全排列

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

namespace ExArrange
{
    class Arrange   

   {
        public void Arrange(int n, int r)
        {
            int i = 0, j;
            string s;
            int[] a = new int[n];
            a[i] = 1;
            while (true)
            {
                if ((a[i] - i) <= (n - r + 1))
                {
                    if (i == (r - 1))
                    {

                        s = "";
                        for (j = 0; j < r; j++)
                        {
                            s = s + Convert.ToString(a[j]) + ",";
                        }
                        // Memo1.Lines.Append(Trim(s));
                        Console.WriteLine(s);
                        a[i] = a[i] + 1;
                        continue;
                    }
                    i = i + 1;
                    a[i] = a[i - 1] + 1;
                }
                else
                {
                    if (i == 0)
                    {
                        break;
                    }
                    i = i - 1;
                    a[i] = a[i] + 1;
                }

            }
        }
        static void Main(string[] args)
        {
            Ex03_19 e = new Ex03_19();
            e.Arrange(6, 3);
        }
    }
}

转载于:https://www.cnblogs.com/ziyiFly/archive/2008/09/10/1288099.html

你可能感兴趣的:(常用算法(C#): 用回溯法找出 n 个自然数中取 r 个数的全排列)