zoukankan      html  css  js  c++  java
  • 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]
    ]

    backtracking

    为了防止值重复,用visited数组标记该元素在每一层递归的时候是否被访问过,注意递归到最底层pop元素回到上层的时候,要把此元素的visited状态改成false

    time: O(n! * n), space: O(n)

    class Solution {
        public List<List<Integer>> permute(int[] nums) {
            List<List<Integer>> res = new ArrayList<>();
            boolean[] visited = new boolean[nums.length];
            backtracking(nums, 0, visited, new ArrayList<>(), res);
            return res;
        }
        
        private void backtracking(int[] nums, int idx, boolean[] visited, List<Integer> tmp, List<List<Integer>> res) {
            if(tmp.size() == nums.length) res.add(new ArrayList<>(tmp));
            
            for(int i = 0; i < nums.length; i++) {
                if(visited[i]) continue;
                visited[i] = true;
                tmp.add(nums[i]);
                backtracking(nums, i + 1, visited, tmp, res);
                tmp.remove(tmp.size() - 1);
                visited[i] = false;
            }
        }
    }
  • 相关阅读:
    ajax的调用
    jqurey的应用
    php数据访问数据层
    php租房子练习
    php投票
    Thinkphp 控制器
    ThinkPHP 框架基础
    php留言板
    php上传文件及头像预览
    php文件操作
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10077701.html
Copyright © 2011-2022 走看看