zoukankan      html  css  js  c++  java
  • [leetcode] 46. 全排列(Java)

    46. 全排列

    这题我们可以借用31. 下一个排列写的nextPermutation函数来做,稍微改造一下即可

    注意要先给nums排个序

    class Solution {
        // 当没有下一个排列时return false
        public boolean nextPermutation(int[] nums) {
            if (nums.length == 1) {
                return false;
            }
            int p = -1;
            for (int i = nums.length - 2; i >= 0; i--) {
                if (nums[i] < nums[i + 1]) {
                    p = i;
                    break;
                }
            }
    
            if (p != -1) {
                int tmp = nums[p];
                int q = nums.length - 1;
                while (nums[q] <= tmp) {
                    q--;
                }
    
                nums[p] = nums[q];
                nums[q] = tmp;
    
                reverse(p + 1, nums);
            } else {
    //            reverse(0, nums);
                return false;
            }
    
            return true;
        }
    
    
        public void reverse(int k, int[] nums) {
            if (k >= nums.length) return;
            int i = k;
            int j = nums.length - 1;
            while (i < j) {
                int tmp = nums[i];
                nums[i] = nums[j];
                nums[j] = tmp;
                i++;
                j--;
            }
        }
    
        public List<List<Integer>> permute(int[] nums) {
            Arrays.sort(nums);
            List<List<Integer>> ans = new ArrayList<>();
            do {
                List<Integer> tmp = new ArrayList<>();
                for (int num : nums) {
                    tmp.add(num);
                }
                ans.add(tmp);
            } while (nextPermutation(nums));
            return ans;
        }
    }
    
  • 相关阅读:
    easy-batch job processors
    easy-batch job marshallers
    easy-batch job mappers
    easy-batch job filters
    easy-batch job writers
    easy-batch job readers
    easy-batch job 报告
    easy-batch job 调度
    easy-batch job 监控
    easy-batch job 配置
  • 原文地址:https://www.cnblogs.com/acbingo/p/9350290.html
Copyright © 2011-2022 走看看