[Backtracking] [leetcode] Determine whether a number can be expressed as a sum of powers of three

topic:

Give you an integer n, if you can express n as the sum of several different powers of three, please return true, otherwise please return false.

For an integer y, if there is an integer x that satisfies y = 3 ^ x, we call this integer y a power of three.

Example 1:

Input: n = 12
Output: true
Explanation: 12 = 31 + 32

prompt:

  • 1 <= n <= 10^7

source:

1780. Determine whether a number can be expressed as a sum of powers of three

Problem-solving ideas: backtracking

All 3 composed of an array of powers, to find out from the array and n is the number of a few, with and for the target number of combinations of very similar there, you can take over according to write.

  • Number of groups of powers of 3: Calculate the value of each power in advance to form an array, because n is less than 10000000, it can be calculated to 4782969, a total of 15 numbers.
  • path: Because there is no need to return each combination, just return whether there is or not, so the path variable does not need to be defined. Without path, this problem can be counted as a recursive problem.
  • The result meets the conditions: current and consistent with the goal
  • Pruning condition: when found, or when the current and + subsequent numbers are greater than n

code show as below:

static int nums[15] = {1,3,9,27,81,243,729,2187,6561,19683,59049,177147,531441,1594323,4782969};
class Solution {
public:
    //vector<int> path;
    bool ok;
    bool checkPowersOfThree(int n) {
        ok = false;
        back(n, 0, 0);
        return ok;
    }
    void back(int n, int sum, int start) {
        if (n == sum) {
            ok = true;
            return;
        }
        for (int i = start; i < 15; i++) {
            if (ok || sum + nums[i] > n) break;
            //path.push_back(nums[i]);
            back(n, sum + nums[i], i+1);
            //path.pop_back();
        }
    }
};

 

Guess you like

Origin blog.csdn.net/hbuxiaoshe/article/details/115048058