60. Permutation Sequence

来源:互联网 发布:ubuntu nano命令 编辑:程序博客网 时间:2024/06/06 20:09

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.

程序如下:

class Solution {    private int cnt = 0;    private String str = "";    public void swap(char[] array, int i, int j){        char tmp = array[i];        array[i] = array[j];        array[j] = tmp;    }    public void backTracing(char[] array, int start, int k){        if (cnt == k){            return;        }        if (start >= array.length){            cnt ++;            if (cnt == k){                str = new String(array);            }            return;        }        for (int i = start; i < array.length; ++ i){            swap(array, start, i);            backTracing(array, start + 1, k);        }        for (int i = start; i < array.length - 1; ++ i){            swap(array, i, i + 1);        }    }        public String getPermutation(int n, int k) {        char[] ch = new char[n];        for (int i = 0; i < ch.length; ++ i){            ch[i] = (char)(i + 1 + '0');        }        backTracing(ch, 0, k);        return str;    }}



原创粉丝点击