设为首页 加入收藏

TOP

LeetCode 59 Permutation Sequence
2015-07-20 17:48:54 来源: 作者: 【 】 浏览:5
Tags:LeetCode Permutation Sequence

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.

    Note: Given n will be between 1 and 9 inclusive.

    思路,使用字典序法,与http://blog.csdn.net/mlweixiao/article/details/38897499

    public class Solution {
    	
    	private void nextPermutation(int[] num) {
    		int i;
    		int cur = -1;
    		int temp;
    		// find the last increase sequence
    		for (i = num.length - 1; i >= 1; i--) {
    			if (num[i] > num[i - 1]) {
    				cur = i - 1;
    				break;
    			}
    		}
    
    		// if the increase sequence exists,
    		// swap the cur and the last one(bigger than it)
    		if (cur != -1) {
    			for (i = num.length - 1; i > cur; i--) {
    				if (num[i] > num[cur]) {
    					temp = num[cur];
    					num[cur] = num[i];
    					num[i] = temp;
    					break;
    				}
    			}
    		}
    
    		for (i = cur + 1; 2 * i <= cur + num.length - 1; i++) {
    			temp = num[i];
    			num[i] = num[num.length - i + cur];
    			num[num.length - i + cur] = temp;
    		}
    	}
    	
        public String getPermutation(int n, int k) {
            int [] temp=new int[n];
            StringBuffer s=new StringBuffer("");
            
            for(int i=0;i
        
         

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇C++实现堆排序 下一篇VC++实用宏定义

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·C语言中如何将结构体 (2025-12-24 22:20:09)
·纯C语言结构体成员变 (2025-12-24 22:20:06)
·C语言中,指针函数和 (2025-12-24 22:20:03)
·哈希表 - 菜鸟教程 (2025-12-24 20:18:55)
·MySQL存储引擎InnoDB (2025-12-24 20:18:53)