0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

順列の組み合わせ全列挙(再帰関数の理解含む)

Posted at

概要

再帰関数といえば順列の組み合わせ数の計算としてよく出てくる
この辺とかである
https://qiita.com/drken/items/23a4f604fa3f505dd5ad#1-%E5%86%8D%E5%B8%B0%E9%96%A2%E6%95%B0%E3%81%A8%E3%81%AF

ただ、組み合わせ自体をすべて列挙する関数が自分がググった限りではあまりなかったので実装してみた。
ちなみに元々は
https://atcoder.jp/contests/abc236/tasks/abc236_d
から二人選ぶ組み合わせを計算してみたかったですが、全然やり方わからん・・・となっていた

main.rs
fn dfs( s:&mut usize, used:&mut Vec<bool>, ans:&mut Vec<usize>){

  if used.iter().all(|&f| f){
    *s += 1;
    println!("{:?}_{}",ans,"OK");
  }
  let num = used.len();
  for i in 0..num{
    if used[i] {continue}
    used[i] =true;
    ans.push(i);
    dfs(s,used,ans);
    used[i] = false;
    ans.pop();
  }

}

fn main() {
let mut s =0;
let mut used = vec![false;4];
let mut ans =vec![];

dfs(&mut s,&mut used,&mut ans);

println!("{:?}_{}",s,"OK");
}

このときの出力は下記のようになる。やっと再帰関数が分かってきた気がする。
[0, 1, 2, 3]_OK
[0, 1, 3, 2]_OK
[0, 2, 1, 3]_OK
[0, 2, 3, 1]_OK
[0, 3, 1, 2]_OK
[0, 3, 2, 1]_OK
[1, 0, 2, 3]_OK
[1, 0, 3, 2]_OK
[1, 2, 0, 3]_OK
[1, 2, 3, 0]_OK
[1, 3, 0, 2]_OK
[1, 3, 2, 0]_OK
[2, 0, 1, 3]_OK
[2, 0, 3, 1]_OK
[2, 1, 0, 3]_OK
[2, 1, 3, 0]_OK
[2, 3, 0, 1]_OK
[2, 3, 1, 0]_OK
[3, 0, 1, 2]_OK
[3, 0, 2, 1]_OK
[3, 1, 0, 2]_OK
[3, 1, 2, 0]_OK
[3, 2, 0, 1]_OK
[3, 2, 1, 0]_OK

ちなみにitertoolsを使うと簡単に書けます.これで上と同じ出力が得られる。
https://docs.rs/itertools/0.10.3/itertools/trait.Itertools.html#method.permutations

fn main() {
  let perms = (0..4).permutations(4);
  for i in perms{
    println!("{:?}",i);
  }
}

ちなみに順列組み合わせは実装できていない。つらい

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?