Leetcode - Permutations

Leetcode - Permutations_第1张图片
Paste_Image.png

My code:

import java.util.ArrayList;
import java.util.List;

public class Solution {
    public List> permute(int[] nums) {
        if (nums == null || nums.length == 0)
            return null;
        ArrayList> result = new ArrayList>();
        ArrayList permutations = new ArrayList();
        boolean[] isVisited = new boolean[nums.length];
        getPermutations(nums, isVisited, permutations, result);
        return result;
    }
    
    private void getPermutations(int[] nums, boolean[] isVisited, ArrayList permutations
                                    , ArrayList> result) {
        if (permutations.size() == nums.length)
            result.add(new ArrayList(permutations));
        else {
            for (int i = 0; i < nums.length; i++) {
                if (isVisited[i])
                    continue;
                permutations.add(nums[i]);
                isVisited[i] = true;
                getPermutations(nums, isVisited, permutations, result);
                permutations.remove(permutations.size() - 1);
                isVisited[i] = false;
            }
        }
    }
    
    public static void main(String[] args) {
        Solution test = new Solution();
        int[] a = {1, 2, 3};
        System.out.println(test.permute(a));
    }
}

My test result:

Leetcode - Permutations_第2张图片
Paste_Image.png

这道题目不是和之前的combinations很像么。为什么没做出来。
combination 是指定了k,但是顺序固定。
这道题目简单些,顺序不固定,但长度固定。所以每一次都可以用for循环遍历。然后设置一个布尔数组,表示那些被访问过哪些没被访问过就行。

**
总结: backtracing
**

Anyway, Good luck, Richardo!

My code:

public class Solution {
    public List> permute(int[] nums) {
        ArrayList> ret = new ArrayList>();
        if (nums == null || nums.length == 0)
            return ret;
        ArrayList group = new ArrayList();
        boolean[] isVisited = new boolean[nums.length];
        helper(nums.length, nums, isVisited, group, ret);
        return ret;
    }
    
    private void helper(int k, int[] nums, boolean[] isVisited, 
                                        ArrayList group, ArrayList> ret) {
        if (k <= 0) {
            ret.add(new ArrayList(group));
            return;
        }
        else {
            for (int i = 0; i < nums.length; i++) {
                if (isVisited[i])
                    continue;
                else {
                    group.add(nums[i]);
                    isVisited[i] = true;
                    helper(k - 1, nums, isVisited, group, ret);
                    isVisited[i] = false;
                    group.remove(group.size() - 1);
                }
            }
        }
    }
}

一开始做的太浮躁,觉得以前做过,也很熟练,就上手开始写,没思考清楚。
切忌,不要上手就写,即使多么熟练。一定要先想清楚整体思路,再开始写!

Anyway, Good luck, Richardo!

你可能感兴趣的:(Leetcode - Permutations)