LeetCode [46] The whole arrangement (the JAVA)

Address original title: https://leetcode-cn.com/problems/permutations/

Description Title:
Given a sequence of numbers is not repeated, all possible return to full permutation.

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

Problem-solving programs:

[46] LeetCode full array (C ++)

One year later, it becomes difficult to write back ioi had a lot to say how simple this is nonsense ...

Code:

class Solution {
    List<List<Integer>> res;
    public List<List<Integer>> permute(int[] nums) {
        res = new ArrayList<>();
        List<Integer> ans = new ArrayList<>();
        boolean[] visited = new boolean[nums.length];
        backtrack(visited, nums, ans);
        return res;
    }
    public void backtrack(boolean[] visited, int[] nums, List<Integer> ans)
    {
        
        int n = nums.length;
        if(ans.size() == n)
            res.add(new ArrayList(ans));
        for(int i = 0; i < n; i ++)
        {
            if(visited[i] == false)
            {
                visited[i] = true;
                ans.add(nums[i]);
                backtrack(visited, nums, ans);
                ans.remove(ans.size() - 1);
                visited[i] = false;
            }
        }
    }
}
Published 110 original articles · won praise 4 · Views 9311

Guess you like

Origin blog.csdn.net/rabbitsockx/article/details/104701987