< 返回版块

xiami 发表于 2024-05-13 07:45

不是力扣的题, 起因是想编写代码扫未注册的6数字的xyz域名, 起初用rust写, rust的itertools包中有combinations, permutations 但是没有product, 尝试用rust模拟, 由于我也是新手惭愧的说写了半天(是真的半天), 过程中发现能复习不少的rust内容, 于是发出来

fn python_product(nums: Vec<i32>, repeat: i32) -> Vec<Vec<i32>> {
    // code
}

输入:nums = Vec![1, 2, 3], repeat= 3

输出:[[1, 1, 1], [1, 1, 2], [1, 1, 3], [1, 2, 1], [1, 2, 2], [1, 2, 3], [1, 3, 1], [1, 3, 2], [1, 3, 3], [2, 1, 1], [2, 1, 2], [2, 1, 3], [2, 2, 1], [2, 2, 2], [2, 2, 3], [2, 3, 1], [2, 3, 2], [2, 3, 3], [3, 1, 1], [3, 1, 2], [3, 1, 3], [3, 2, 1], [3, 2, 2], [3, 2, 3], [3, 3, 1], [3, 3, 2], [3, 3, 3]]

解释:3 份 nums 的全排列。

评论区

写评论
作者 xiami 2024-05-28 22:33

我是想不出来这个方法, 大佬太6了

--
👇
ZZG: 非递归的也比较好写,比较经典的BFS,为了性能更好还可以把VecDeque换成Vec,不过换成Vec后排列的顺序就不是从(1,1,1)递增到(3,3,3)了

fn python_product(nums: Vec<i32>, repeat: i32) -> Vec<Vec<i32>> {
    assert!(repeat > 0); // 只考虑repeat为正数
    let mut ans = VecDeque::new();
    for &num in &nums {
        ans.push_back(vec![num]);
    }
    let mut temp = VecDeque::new();
    for _ in 1..repeat {
        while let Some(p) = ans.pop_front() {
            for &num in &nums {
                let mut new_p = p.clone();
                new_p.push(num);
                temp.push_back(new_p);
            }
        }
        std::mem::swap(&mut ans, &mut temp);
    }
    ans.into()
}
ZZG 2024-05-16 10:23

非递归的也比较好写,比较经典的BFS,为了性能更好还可以把VecDeque换成Vec,不过换成Vec后排列的顺序就不是从(1,1,1)递增到(3,3,3)了

fn python_product(nums: Vec<i32>, repeat: i32) -> Vec<Vec<i32>> {
    assert!(repeat > 0); // 只考虑repeat为正数
    let mut ans = VecDeque::new();
    for &num in &nums {
        ans.push_back(vec![num]);
    }
    let mut temp = VecDeque::new();
    for _ in 1..repeat {
        while let Some(p) = ans.pop_front() {
            for &num in &nums {
                let mut new_p = p.clone();
                new_p.push(num);
                temp.push_back(new_p);
            }
        }
        std::mem::swap(&mut ans, &mut temp);
    }
    ans.into()
}
作者 xiami 2024-05-13 19:12

写得比我简洁多了, 思路一样 你得把 if repeat < 0 修改为 < 1

👇
jimliang: 写了一个简单的递归的,数量一大容易爆栈,有空再写个无栈的

jimliang 2024-05-13 17:13

写了一个简单的递归的,数量一大容易爆栈,有空再写个无栈的

fn combo(nums: &Vec<i32>, repeat: i32, tmp_list: &mut Vec<i32>, result: &mut Vec<Vec<i32>>) {
    if repeat < 0 {
        result.push(tmp_list.clone());
        return;
    }

    for num in nums {
        tmp_list.push(*num);
        combo(nums, repeat - 1, tmp_list, result);
        tmp_list.pop().unwrap();
    }
}

fn python_product(nums: Vec<i32>, repeat: i32) -> Vec<Vec<i32>> {
    let mut result = vec![];
    let mut tmp_list = vec![];

    combo(&nums, repeat, &mut tmp_list, &mut result);

    result
}
Borber 2024-05-13 10:10

想知道具体扫描的逻辑 ヽ(≧□≦)ノ

1 共 5 条评论, 1 页