LeetCode--No.46--Permutations

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]
]

絕對是經典題啊
還記得當初在cts的辦公室裏刷這道題的時候,把解法打印出來每天看一遍都不是很能理解,現在終於可以自己刷出來了,還是蠻感動的。

class Solution {
    public List<List<Integer>> permute(int[] nums) {
        int[] visited = new int[nums.length];
        Arrays.fill(visited, 0);
        List<List<Integer>> res = new ArrayList<>();
        permuteHelper(nums, visited, new ArrayList<>(), res);
        return res;
    }
    private void permuteHelper(int[] nums, int[] visited, List<Integer> curr, List<List<Integer>> res){
        if (curr.size() == nums.length){
            res.add(new ArrayList<Integer>(curr));
            return;
        }
        for(int i = 0; i < visited.length; i++){
            if (visited[i] == 0){
                visited[i] = 1;
                curr.add(nums[i]);
                permuteHelper(nums, visited, curr, res);
                visited[i] = 0;
                curr.remove(curr.size() - 1);
            }
        }
        return;
    }
}

解題關鍵依然是:
感覺可以算作是DFS吧
1. 搞一個helper函數, 這樣可以recursive的調用
2. 需要一個visited 的東西來記錄節點是不是已經訪問過。
3. 在訪問過之後,要重新設置回來、
4. 設置好一個結束條件,這樣可以return

在這道題裏面,一開始犯了一個錯誤,就是res.add(visited). 然而我們加進來的是visited的指針,並不是數組本身。

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