总计n的完美平方数的最少数量

时间:2017-07-18 09:57:02

标签: algorithm python-3.x data-structures dynamic-programming discrete-mathematics

问题是:

  

给定正整数n,找到总和为n的最小正方数(例如,1,4,9,16 ......)。 Link问题

示例

给定n = 12,返回3,因为12 = 4 + 4 + 4;给定n = 13,返回2,因为13 = 4 + 9。

注意

  

我采用的方法类似于允许重复的整数背包问题。首先,我计算了所有小于n的完美正方形。现在,一旦我拥有它们,问题类似于整数背包问题。我有一个数字n和一个数字列表。我想从列表中选择最小数量,使其总和等于n。这个问题有一个我用过的DP解决方案。

     

在586个测试用例中,我通过了562个测试用例并在下一个测试用例中获得了 TLE 。该测试用例的n值为3428。

我提交的解决方案:

public object GenericMethod(object obj)
{
    // modify the object in some (arbitrary) way
    IEnumerable<FieldInfo> fields = obj.GetType().GetRuntimeFields();
    foreach (var field in fields)
    {
        if (field.FieldType == typeof(string))
        {
            field.SetValue(obj, "This field's string value was modified");
        }
    }

    return obj;
}

提前致谢。

2 个答案:

答案 0 :(得分:2)

您可以将解决方案简化为:

AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    _mainContext = [appDelegate manageObjectContext];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Student"];

    // Add Sort Descriptors
    [fetchRequest setSortDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:NO]]];

    //[fetchRequest setRelationshipKeyPathsForPrefetching: @"detail"];
    // Initialize Fetched Results Controller
    self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:_mainContext sectionNameKeyPath:nil cacheName:nil];

    // Configure Fetched Results Controller
    [self.fetchedResultsController setDelegate:self];

    // Perform Fetch
    NSError *error = nil;
    [self.fetchedResultsController performFetch:&error];

这避免了使用:

  1. self.min函数
  2. 内循环中的除法/模运算。
  3. 2d数组
  4. 并且快两倍。

答案 1 :(得分:0)

有点晚了,但是我相信这个答案可以像我一样帮助其他人。以下是O(sqrt(n))时间复杂度最快的解决方案

  

它基于Lagrange’s four-square theorem   每个自然数都可以表示为四个整数平方的和。   因此答案将是1、2、3或4。

class Solution:
    def is_perfect(self, n):
        x = int(math.sqrt(n))
        return x * x == n

    def numSquares(self, n: int) -> int:
        if n < 4:
            return n

        if self.is_perfect(n):  # number is a perfect square
            return 1

        # the result is 4 if number = 4^k*(8*m + 7)
        while n & 3 == 0:  # while divisible by 4
            n >>= 2
        if n & 7 == 7:  # 8m+7 => last 3 digits = 111
            return 4

        x = int(math.sqrt(n))
        for i in range(1, x + 1):  # sum of 2 perfect squares
            if self.is_perfect(n - i * i):
                return 2

        return 3  # by elimination