这个题蛮有意思的,可以直接从后遍历,遇到一个数就把所有子集加上该数组成新的子集,遍历完毕即是所有子集
(nums: Vec<i32>)
| 1 | // 这个题蛮有意思的,可以直接从后遍历,遇到一个数就把所有子集加上该数组成新的子集,遍历完毕即是所有子集 |
| 2 | pub fn subsets(nums: Vec<i32>) -> Vec<Vec<i32>> { |
| 3 | let mut res: Vec<Vec<i32>> = vec!(vec!()); |
| 4 | for num in nums { |
| 5 | for i in 0..res.len() { // 这里只能用index,因为res在循环里面变化 |
| 6 | let mut tmp = res[i].clone(); |
| 7 | tmp.push(num); |
| 8 | res.push(tmp); |
| 9 | } |
| 10 | } |
| 11 | res |
| 12 | } |
| 13 | |
| 14 | fn main() { |
| 15 | let nums = vec![1,2,3]; |