LeetCode實戰:全排列

題目英文

Given a collection of distinct integers, return all possible permutations.

Example:

Input: [1,2,3]
Output:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]

題目中文

給定一個沒有重複數字的序列,返回其所有可能的全排列。

示例:

輸入: [1,2,3]
輸出:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]

算法實現

回溯法(back tracking) 是一種選優搜索法,又稱爲試探法,按選優條件向前搜索,以達到目標。但當探索到某一步時,發現原先選擇並不優或達不到目標,就退回一步重新選擇,這種走不通就退回再走的技術爲回溯法,而滿足回溯條件的某個狀態的點稱爲“回溯點”。

白話:回溯法可以理解爲通過選擇不同的岔路口尋找目的地,一個岔路口一個岔路口的去嘗試找到目的地。如果走錯了路,繼續返回來找到岔路口的另一條路,直到找到目的地。

本練習的回溯過程如下所示:

回溯過程

public class Solution
{
    private IList<IList<int>> _result;
    private bool[] _used;

    public IList<IList<int>> Permute(int[] nums)
    {
        _result = new List<IList<int>>();
        if (nums == null || nums.Length == 0)
            return _result;
        _used = new bool[nums.Length];

        FindPath(nums, 0, new List<int>());
        return _result;
    }

    public void FindPath(int[] nums, int count, List<int> path)
    {
        if (count == nums.Length)
        {
            //遞歸終止條件
            List<int> item = new List<int>();
            item.AddRange(path);
            //加入拷貝
            _result.Add(item);
            return;
        }
        for (int i = 0; i < nums.Length; i++)
        {
            if (_used[i] == false)
            {
                path.Add(nums[i]);
                _used[i] = true;
                FindPath(nums, count + 1, path);
                path.RemoveAt(path.Count - 1);
                _used[i] = false;
            }
        }
    }
}

實驗結果

  • 狀態:通過
  • 25 / 25 個通過測試用例
  • 執行用時: 364 ms, 在所有 C# 提交中擊敗了 80.00% 的用戶
  • 內存消耗: 30.6 MB, 在所有 C# 提交中擊敗了 7.14% 的用戶

提交結果


相關圖文

1. “數組”類算法

2. “鏈表”類算法

3. “棧”類算法

4. “隊列”類算法

5. “遞歸”類算法

6. “字符串”類算法

7. “樹”類算法

8. “哈希”類算法

9. “搜索”類算法

10. “動態規劃”類算法

11. “數值分析”類算法

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章