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

Jan 19 - Permutation Sequence; BackTracking; Factorial;

时间:2016-01-20 07:38:03      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:

Code:

public class Solution {
    public static String getPermutation(int n, int k) {
        String result = "";
        if(n == 1) return result + 1;
        int factorial_n = factorial(n-1);
        boolean[] isUsed = new boolean[n];
        return addDigit(factorial_n, k-1, n-1, isUsed);
    }
    
    public static int factorial(int n){
        if(n == 1 || n == 0) return 1;
        return n*factorial(n-1);
    }
    
    public static String addDigit(int factorial, int k, int n, boolean[] isUsed){
    	int times = k/factorial;
        int remain = k%factorial;
            int i = 0;
            int count = 0;
            for(; i < isUsed.length; i++){
                if(!isUsed[i]) count++;
                if(count == times+1) break;
                    
            }
            isUsed[i] = true;
            if(n == 0) return String.valueOf(i+1);
            if(n == 1){
            	String s = i+1+addDigit(1, remain, n-1, isUsed);
            	System.out.println("n == 1: "+ (i+1));
            	return s;
            }
            String s = i+1+addDigit(factorial/n, remain, n-1, isUsed);
            return s;
    }
}

  

Jan 19 - Permutation Sequence; BackTracking; Factorial;

标签:

原文地址:http://www.cnblogs.com/5683yue/p/5143944.html

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