添加 0017.电话号码的字母组合 0077.组合 0077.组合优化 0216.组合总和III Rust版本

添加 0017.电话号码的字母组合 0077.组合 0077.组合优化 0216.组合总和III Rust版本
This commit is contained in:
BaoTaoqi
2022-07-10 09:09:02 +08:00
parent 821cca116c
commit e2d16c5894
4 changed files with 148 additions and 0 deletions

View File

@@ -535,6 +535,56 @@ func backtrack(n,k,start int,track []int){
}
```
### Rust
```Rust
impl Solution {
fn backtracking(result: &mut Vec<Vec<i32>>, path: &mut Vec<i32>, n: i32, k: i32, startIndex: i32) {
let len= path.len() as i32;
if len == k{
result.push(path.to_vec());
return;
}
for i in startIndex..= n {
path.push(i);
Self::backtracking(result, path, n, k, i+1);
path.pop();
}
}
pub fn combine(n: i32, k: i32) -> Vec<Vec<i32>> {
let mut result: Vec<Vec<i32>> = Vec::new();
let mut path: Vec<i32> = Vec::new();
Self::backtracking(&mut result, &mut path, n, k, 1);
result
}
}
```
剪枝
```Rust
impl Solution {
fn backtracking(result: &mut Vec<Vec<i32>>, path: &mut Vec<i32>, n: i32, k: i32, startIndex: i32) {
let len= path.len() as i32;
if len == k{
result.push(path.to_vec());
return;
}
// 此处剪枝
for i in startIndex..= n - (k - len) + 1 {
path.push(i);
Self::backtracking(result, path, n, k, i+1);
path.pop();
}
}
pub fn combine(n: i32, k: i32) -> Vec<Vec<i32>> {
let mut result: Vec<Vec<i32>> = Vec::new();
let mut path: Vec<i32> = Vec::new();
Self::backtracking(&mut result, &mut path, n, k, 1);
result
}
}
```
### C
```c
int* path;