Permutation and Combination

PUBLISHED: MAY 2, 20261 MIN READ

Permutation & Combination⭐ 1. Permutation (P)Order matters.Selecting and arranging items.Formula⭐ 2. Combination (C)Order does not matter.Only selecting ite

Divya Sachan
Divya SachanAuthor
slowking
#199
slowking

Permutation & Combination

1. Permutation (P)

  • Order matters.
  • Selecting and arranging items.

Formula

P(n,r)=n!(nr)!P(n,r)=\frac{n!}{(n-r)!}

2. Combination (C)

  • Order does not matter.
  • Only selecting items.

Formula

C(n,r)=n!r!(nr)!C(n,r)=\frac{n!}{r!(n-r)!}

They are related as:

P(n,r)=C(n,r)r!P(n,r)=C(n,r)\cdot r!

The recursive algorithm to generate all permutation of array of characters (string)

cpp
void permute(char arr[], int i, int n) {
    if(i == n){
        print(arr);
        return;
    }

    for (int j = i; j<= n; j++) {
        swap(arr[i], arr[j]);
        permute(arr, i + 1, n);
        swap(arr[i], arr[j]); // backtrack
    }
}

Recursion tree for permutation of the string "ABC"

Recursion tree for string permutations showing swaps and fixed characters to generate all permutations of ABC.