zoukankan      html  css  js  c++  java
  • Permutations 解答

    Question

    Given a collection of numbers, return all possible permutations.

    For example,
    [1,2,3] have the following permutations:
    [1,2,3][1,3,2][2,1,3][2,3,1][3,1,2], and [3,2,1].

    Solution

    Traditional backtracking  way to solve this problem.

     1 public class Solution {
     2     public List<List<Integer>> permute(int[] nums) {
     3         Arrays.sort(nums);
     4         int length = nums.length;
     5         List<List<Integer>> result = new ArrayList<List<Integer>>();
     6         boolean[] visited = new boolean[length];
     7         
     8         dfs(nums, visited, new ArrayList<Integer>(), result);
     9         return result;
    10     }
    11     
    12     private void dfs(int[] nums, boolean[] visited, List<Integer> record, List<List<Integer>> result) {
    13         if (record.size() == nums.length) {
    14             if (!result.contains(record))
    15                 result.add(new ArrayList<Integer>(record));
    16             return;
    17         }
    18         for (int i = 0; i < nums.length; i++) {
    19             if (!visited[i]) {
    20                 record.add(nums[i]);
    21                 visited[i] = true;
    22                 dfs(nums, visited, record, result);
    23                 // Restore
    24                 record.remove(record.size() - 1);
    25                 visited[i] = false;
    26             }
    27         }
    28     }
    29 }

    Another solution is that we don't need to store visited status, but we just need to modify "nums" object.

     1 class Solution:
     2     def dfs(self, nums: List[int], record: List[int], result: List[List[int]]) -> None:
     3         if not nums:
     4             result.append(record)
     5         for i in range(len(nums)):
     6             self.dfs(nums[:i] + nums[i + 1:], record + [nums[i]], result)
     7     
     8     def permute(self, nums: List[int]) -> List[List[int]]:
     9         result = []
    10         self.dfs(nums, [], result)
    11         return result
  • 相关阅读:
    Vue 获取dom元素中的自定义属性值
    php文件包含
    php数组运算符
    管理一组事物的状态
    php数据类型转换
    php函数
    PHP循环while do while循环
    php的流程控制 if elseif swich case for循环
    php的工作原理
    python算数、逻辑运算,位运算
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4884556.html
Copyright © 2011-2022 走看看