码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode - Permutation Sequence

时间:2015-12-27 17:36:41      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:

题目:

The set [1,2,3,…,n] contains a total of n! unique permutations.

By listing and labeling all of the permutations in order,
We get the following sequence (ie, for n = 3):

  1. "123"
  2. "132"
  3. "213"
  4. "231"
  5. "312"
  6. "321"

Given n and k, return the kth permutation sequence.

思路:

除法和求余运算,对每一组数往下递推

package permutation;

import java.util.ArrayList;
import java.util.List;

public class PermutationSequence {

    public String getPermutation(int n, int k) {
        List<Integer> l = new ArrayList<Integer>();
        for (int i = 1; i <= n; ++i) 
            l.add(i);
        --k;
        StringBuilder sb = new StringBuilder();
        for (int i = n; i > 0; --i) {
            int fib = fib(i - 1);
            int index = k / fib;
            k = k % fib;
            sb.append((char)(‘0‘ + l.get(index)));
            l.remove(index);
        }
        return sb.toString();
    }
    
    private int fib(int n) {
        int res = 1;
        for (int i = 1; i <= n; ++i)
            res *= i;
        return res;
    }
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        PermutationSequence p = new PermutationSequence();
        System.out.println(p.getPermutation(4, 5));
    }

}

 

LeetCode - Permutation Sequence

标签:

原文地址:http://www.cnblogs.com/shuaiwhu/p/5080251.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!