• LeetCode Permutation Sequence


    class Solution {
    public:
        string getPermutation(int n, int k) {
            k--;
            if (n < 1 || k < 0) return "";
    
            vector<int> nums(n, 0);
            long seg = 1;
            for (int i=0; i<n; i++) {
                nums[i] = i + 1;
                seg = seg * (nums[i]);
            }
            if (k >= seg) return "";    
            int idx = 0;
    
            for (int i=0; i < n-1; i++) {
                seg = seg / (n - i);
                idx = k / seg + i;
                k = k % seg;
    
                int sel = nums[idx];
    
                for (int j = idx; j>i; j--) {
                    nums[j] = nums[j - 1];
                }
    
                nums[i] = sel;
            }
            string res;
            for (int i=0; i<n; i++) {
                res.push_back((char)(nums[i] + '0'));
            }
            return res;
        }
    };

    复杂度O(n^2), 但是因为参数k用int表示了,说明n的值不会太大,否则n!(k最大值)轻轻松松超过int范围

    第二轮:

    class Solution {
    public:
        string getPermutation(int n, int k) {
            int mag[10] = {1};
            for (int i=1; i<n; i++) {
                mag[i] = mag[i-1] * i;
            }
            string res;
            
            int idx = n - 1;
            int ds[] = {1,2,3,4,5,6,7,8,9};
            k--;
            
            while (idx >= 0) {
                int d = k / mag[idx];
                k = k % mag[idx];
                for (int i=0; i<9; i++) {
                    if (d == 0 && ds[i] != 0) {
                        d = ds[i];
                        ds[i] = 0;
                        break;
                    }
                    if (ds[i] != 0) {
                        d--;
                    }
                }
                res.push_back('0' + d);
                idx--;
            }
            return res;
        }
    };
  • 相关阅读:
    SpringData概述
    运行javac 报告javac不是内部或外部命令,但是运行java、java-version正常
    Spring Data JPA
    spring-data-jpa 介绍 复杂查询,包括多表关联,分页,排序等
    Thymeleaf使用说明
    Specifications查询
    OA项目_环境搭建
    anu
    anu
    anu
  • 原文地址:https://www.cnblogs.com/lailailai/p/3758452.html
Copyright © 2020-2023  润新知