-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathzi-fu-chuan-de-pai-lie-lcof.rs
86 lines (72 loc) · 2.11 KB
/
zi-fu-chuan-de-pai-lie-lcof.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#![allow(dead_code, unused, unused_variables, non_snake_case)]
use std::vec;
fn main() {
println!("{:?}", Solution::permutation("abc".to_string()));
}
struct Solution;
impl Solution {
pub fn permutation1(s: String) -> Vec<String> {
Self::f(s.as_bytes())
.into_iter()
.map(|x| String::from_utf8(x).unwrap())
.collect::<std::collections::HashSet<String>>()
.into_iter()
.collect()
}
fn f(x: &[u8]) -> Vec<Vec<u8>> {
if x.len() == 1 {
return vec![vec![x[0]]];
}
let mut data = vec![];
for i in 0..x.len() {
let n = x[i];
let mut v = Vec::with_capacity(x.len());
v.extend(&x[0..i]);
v.extend(&x[i + 1..]);
let x1 = Self::f(&v[..]);
for j in x1.iter() {
let mut m = Vec::with_capacity(x.len());
m.push(n);
m.extend(j.into_iter());
data.push(m);
}
}
data
}
pub fn permutation(s: String) -> Vec<String> {
let mut s = s;
unsafe {
let bytes = s.as_bytes_mut();
bytes.sort();
}
let mut data = vec![s];
let mut index = 0;
while index < data.len() {
match Self::next_permutation(data[index].clone()) {
Some(s) => data.push(s),
None => break,
}
index += 1;
}
data
}
pub fn next_permutation(mut string: String) -> Option<String> {
unsafe {
let s = string.as_bytes_mut();
for i in (0..s.len() - 1).rev() {
if s[i] < s[i + 1] {
let mut min = i + 1;
for j in (i + 1..s.len()).rev() {
if s[j] > s[i] && s[j] < s[min] {
min = j;
}
}
s.swap(i, min);
s[i + 1..].sort();
return Some(string);
}
}
None
}
}
}