1
2

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 5 years have passed since last update.

備忘録

Last updated at Posted at 2019-02-23

コード備忘録

ネットで見つけた便利なコードサンプル

全組み合わせの列挙

引用元はこちら
解説はこちら

・順列

    public static void permutation(String q, String ans){
        // Base Case
        if(q.length() <= 1) {
            System.out.println(ans + q);
        }
        // General Case
        else {
            for (int i = 0; i < q.length(); i++) {
                permutation(q.substring(0, i) + q.substring(i + 1),
                        ans + q.charAt(i));
            }
        }
    }

・組合わせ

    public static void combination(String q, String ans, int k){
        // Base Case
        if(ans.length() == k) {
            System.out.println(ans);
        }
        // General Case
        else {
            while (q.length() > 0) {
                combination(q.substring(1), ans + q.charAt(0), k);
                q = q.substring(1);
            }
        }
    }
    public static void main(String[] args) {
        combination("abcd", "", 2);
    }

・第2引数ansをprivateなコンストラクタのように扱う


public static void permutation(String q){
  permutation(q, "");
}

private static void permutation(String q, String ans){
  //省略
}
1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?