1. 程式人生 > 其它 >狀態壓縮dp系列問題總結

狀態壓縮dp系列問題總結

技術標籤:leetcode和機試題leetcode

1、Beautiful Arrangement

題目:

Suppose you havenintegers labeled1throughn. A permutation of thosenintegersperm(1-indexed) is considered abeautiful arrangementif for everyi(1 <= i <= n),eitherof the following is true:

  • perm[i]is divisible byi.
  • iis divisible byperm[i].

Given an integern

, returnthenumberof thebeautiful arrangementsthat you can construct.

Example 1:

Input: n = 2
Output: 2
Explanation: 
The first beautiful arrangement is [1,2]:
    - perm[1] = 1 is divisible by i = 1
    - perm[2] = 2 is divisible by i = 2
The second beautiful arrangement is [2,1]:
    - perm[1] = 2 is divisible by i = 1
    - i = 2 is divisible by perm[2] = 1

Example 2:

Input: n = 1
Output: 1

Constraints:

  • 1 <= n <= 15

程式碼:

class Solution {
public:
    int countArrangement(int n) {
        vector<int> dp(1<<n,0);
        for(int i=0;i<n;i++){
            dp[1<<i]=1;    
        }
        for(int i=0;i<(1<<n);i++){
            long int index=1;
            int temp=i;
            while(temp){
                temp=temp&(temp-1);
                index+=1;
            }
            for(int j=0;j<n;j++){
                //二進位制位為0(未被選取),且能放在第Index位
                if(!(i&(1<<j))&&((j+1)%index==0||index%(j+1)==0)){
                    dp[1<<j|i]+=dp[i];
                }
            }
        }
        return dp[(1<<n)-1];
    }
};

想法:用一個n位的二進位制數表示二進位制中為1的數字已任意順序放在陣列的前m位(m為該二進位制數中1的個數)。