Monday, October 19, 2015

[leetcode] Permutation Sequence

这条题是个数学题
[1,2,....,n]
去掉第一位... 剩下就有 (n-1)!种可能...
所以第一位可以用 k/(n-1)!来求..
然后第二位就剩下 K2 = k%(n-1)!, K2/(n-2)! 来求... 如此类推

public class Solution {
    public String getPermutation(int n, int k) {
        int factor[] = new int[n];
        List nums = new ArrayList();
        factor[0] = 1;
        nums.add(1+"");
        for (int i = 1; i < n; i++){
            factor[i] = factor[i-1]*i;
            nums.add((i+1)+"");
        }
        
        k-=1;
        StringBuilder result = new StringBuilder();
        for (int i = n; i >= 1; i--){
            int j = k / factor[i-1];
            k %= factor[i-1];
            result.append(nums.remove(j));
        }
        
        return result.toString();
    }
}



No comments:

Post a Comment