LeetCode 46. Permutations(dfs)

题目来源:https://leetcode.com/problems/permutations/

问题描述

46. Permutations

Medium

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]

]

------------------------------------------------------------

题意

给定一个序列nums,求序列的全排列。

------------------------------------------------------------

思路

求这种“排列组合”问题首先要想到搜索。具体来说,用dfs(深度优先搜索),dfs方法的两个参数分别是当前排列cur和nums数组中各元素的是否使用。遍历nums中的元素,将没有使用过的元素放入cur中再递归调用dfs,直到cur的长度等于nums则dfs返回。

------------------------------------------------------------

代码

class Solution {
    private List<List<Integer>> ret = new LinkedList<>();
    private int n;
    private int[] _nums;
    
    private void init(int[] nums)
    {
        n = nums.length;
        _nums = nums;
    }
    
    private void dfs(LinkedList<Integer> cur, boolean[] visited)
    {
        if (cur.size() == n)
        {
            ret.add(new LinkedList<Integer>(cur));
            return;
        }
        for (int i=0; i<n; i++)
        {
            if (!visited[i])
            {
                visited[i] = true;
                cur.add(_nums[i]);
                dfs(cur, visited);
                cur.removeLast();
                visited[i] = false;
            }
        }
    }
    
    public List<List<Integer>> permute(int[] nums) {
        init(nums);
        boolean[] visited = new boolean[n];
        LinkedList<Integer> cur = new LinkedList<Integer>();
        dfs(cur, visited);
        return ret;
    }
}

猜你喜欢

转载自blog.csdn.net/da_kao_la/article/details/89084913