iT邦幫忙

1

[C#] 全排列解法

c#
  • 分享至 

  • xImage
  •  

输入:nums = [1,2,3]
输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
示例 2:

输入:nums = [0,1]
输出:[[0,1],[1,0]]
示例 3:

     static void Main(string[] args)
     {
         permute();
     }

     /// <summary>
     /// 輸入一組數字全排列
     /// </summary>
     private static void permute()
     {
         int[] nums = [1, 2, 3];
         List<int> list = new List<int>();
         List<List<int>> lists = new List<List<int>>();
         Backtrack(nums, list, lists);
         foreach (var choose in lists)
         {
             Console.WriteLine(string.Join(", ", choose.ToArray()));
         }
     }

     /// <summary>
     /// 數字全排列遞迴
     /// </summary>
     /// <param name="nums">輸入一組數字清單</param>
     /// <param name="tempList">選擇暫存清單</param>
     /// <param name="lists">最終結果清單</param>
     private static void Backtrack(int[] nums, List<int> tempList, List<List<int>> lists)
     {

         if (nums.Count() == tempList.Count())
         {
             lists.Add(new List<int>(tempList));
         }
         else
         {
             for (int i = 0; i < nums.Length; i++)
             {
                 //如果選過直接 continue
                 if (tempList.Contains(nums[i])) continue;
                 tempList.Add(nums[i]);
                 Backtrack(nums, tempList, lists);
                 //取消之前的選擇
                 tempList.RemoveAt(tempList.Count - 1);
             }
         }
     }

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言