Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit2e1678b

Browse files
author
applewjg
committed
PermutationSequence
Change-Id: I2aa3f982c2d2156f2dd07647289a64ebfd0a8c56
1 parent4987697 commit2e1678b

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

‎PermutationSequence.java

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
/*
2+
Author: King, wangjingui@outlook.com
3+
Date: Dec 20, 2014
4+
Problem: Permutation Sequence
5+
Difficulty: Medium
6+
Source: https://oj.leetcode.com/problems/permutation-sequence/
7+
Notes:
8+
The set [1,2,3,...,n] contains a total of n! unique permutations.
9+
By listing and labeling all of the permutations in order,
10+
We get the following sequence (ie, for n = 3):
11+
"123"
12+
"132"
13+
"213"
14+
"231"
15+
"312"
16+
"321"
17+
Given n and k, return the kth permutation sequence.
18+
Note: Given n will be between 1 and 9 inclusive.
19+
20+
Solution: 1. Brute!
21+
2. combinatorial mathematics.
22+
*/
23+
publicclassSolution {
24+
publicvoidnextPermutation(char[]num) {
25+
intlast =num.length -1;
26+
inti =last;
27+
while (i >0 &&num[i -1] >=num [i]) --i;
28+
for (intl =i,r =last;l <r; ++l, --r) {
29+
num[l] = (char) (num[l] ^num[r]);
30+
num[r] = (char) (num[l] ^num[r]);
31+
num[l] = (char) (num[l] ^num[r]);
32+
}
33+
if (i ==0) {
34+
return;
35+
}
36+
intj =i;
37+
while (j <=last &&num[i-1] >=num[j]) ++j;
38+
num[i-1] = (char) (num[i-1] ^num[j]);
39+
num[j] = (char) (num[i-1] ^num[j]);
40+
num[i-1] = (char) (num[i-1] ^num[j]);
41+
}
42+
publicStringgetPermutation_1(intn,intk) {
43+
char[]num =newchar[n];
44+
for (inti =0;i <n; ++i)num[i] = (char) (i +'1');
45+
System.out.println(String.valueOf(num));
46+
while (--k !=0) {
47+
nextPermutation(num);
48+
}
49+
returnString.valueOf(num);
50+
}
51+
publicStringgetPermutation_2(intn,intk) {
52+
StringBuffersb =newStringBuffer();
53+
StringBufferres =newStringBuffer();
54+
inttotal =1;
55+
for (inti =1;i <=n; ++i) {
56+
total =total *i;
57+
sb.append(i);
58+
}
59+
k--;
60+
while(n !=0) {
61+
total =total /n;
62+
intidx =k /total;
63+
res.append(sb.charAt(idx));
64+
k =k %total;
65+
sb.deleteCharAt(idx);
66+
n--;
67+
}
68+
returnres.toString();
69+
}
70+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp